【问题标题】:Program that reads and writes integers to a file将整数读取和写入文件的程序
【发布时间】:2017-08-23 17:54:30
【问题描述】:

您好,提前谢谢您。这是一个非常简单的问题,但却让我很紧张。我想要的只是要求一个整数写入文件,然后显示每个整数。我已经学会了如何写入文件或从文件中显示,并且我已经成功了,但是当我尝试同时执行这两种操作时,它只会要求我输入整数并且不显示数字。 我认为这可能是与 fstream 或指针位置有关的问题。

这是程序:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <fstream>

using std::cout;
using std::cin;
using std::fstream;
using std::endl;

int a;
int x;

int main() {
    fstream in;

    in.open("op.txt", std::ios::app);

    cout << "Write an integer" << endl;
    cin >> x;
    in << " " << x;

    while (in >> a) {
        cout << a << endl;
        cout << in.tellg();
    }

    in.close();
    return 0;

}

【问题讨论】:

  • 你为什么要同时写和读?您进行读写的方式是顺序的,因此您的猜测是正确的-它与文件指针有关。您需要对文件进行一些“随机访问”,以便读取您刚刚写入文件的内容。检查stackoverflow.com/questions/14393774/…
  • 那么我是否也可以先写 ofstream 并询问数字,然后关闭文件,然后用 ifstream 再次打开以显示整数?感谢您的回答。

标签: c++ visual-studio file integer fstream


【解决方案1】:

有几点需要修复:

in.open("op.txt",std::ios::in | std::ios::out | std::ios::app);

here 是你需要做std::ios::in and out 的原因

第二个问题是当您在文件的写入和读取之间切换时,就像您所说的那样,问题在于读取指针的位置

in.seekg(0, std::ios::beg);//before the while loop;

这会将读取位置设置为 0,因此程序可以从头开始读取文件。here

【讨论】:

  • 好的,终于成功了,非常感谢。我认为 std::ios::in 和 ::out 已经进入“fstream”,现在它可以工作了。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多