我有一个函数,可以逐个字符地从文件中获取输入:
#include <iostream>
#include <fstream>
using namespace std;
ifstream input("sequence.txt");
char getChar(){
char nextType;
if (input.eof()) {
input.clear();
input.seekg(0,ios::beg);
}
input >> nextType;
return nextType;
}
int main(){
for(int i = 0; i < 10; i++){
cout << getChar() << endl;
}
return 0;
}
“sequence.txt”里面的输入是:
I O
所以输出应该交替打印 I 和 O,而是输出:
I O O I O O I O O I
如何在第一次读取文件中的最后一个字符后重置文件?
最佳答案
eof
仅在您已到达文件末尾后尝试读取时设置。相反,首先尝试读取一个字符。如果失败,则重置流并重试,如下所示:
char getChar()
{
char nextType;
if (!(input >> nextType))
{
input.clear();
input.seekg(0,ios::beg);
input >> nextType;
}
return nextType;
}
关于c++ - 为什么在文件重置之前最后一个字符被输入两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17910855/