#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(int argc, char *argv[]) {
	ifstream in_file("test.txt", ios::in);
	if (!in_file) exit(-1);
	string x;
	while (!in_file.eof())
	{	in_file >> x;
		cout << x << endl;
	}
	in_file.close();

	return 0;
}

写一个C++读文件的程序,会发现最后一行被读取了两次

C++重复读取文件最后一行问题&&解决

这不是C++的BUG,而是读完最后一行还没到EOF,while判断仍然为True,可也已经读完整个文件,新string抽取失败,但跳出了空中断,延用了上一次的内容。

解决方法:添加两行代码即可

		 in_file.get(); // 读取最后的回车符
		 if(in_file.peek() == '\n') break;

C++重复读取文件最后一行问题&&解决

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2021-08-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-22
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案