【发布时间】: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