c++ - 为什么在文件重置之前最后一个字符被输入两次?

标签 c++ file-io char eof

我有一个函数,可以逐个字符地从文件中获取输入:

#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/

相关文章:

c++ - 在 C++ 中使用 [] 而不是函数调用

c++ - 使用模板元编程将模板函数 bool 参数转置为运行时函数参数

c++ - 如何将文本文件读入二维数组 - C++

c++ - 我应该在析构函数中写入文件末尾吗?

c - 多个进程,一个互斥锁

c - 初级C练习【sscanf - fgets - if else】

c++ - 如何使 std::vector 类成为一个序列,以便可以将其传递给 boost::hana::group?

c - C 中的字符串搜索操作

C++:如何在文件的输入和输出之间切换?

c++ - Linux VM(重型多线程应用程序)的性能改进