【发布时间】:2013-01-12 21:03:38
【问题描述】:
我正在尝试使用 C++,但在读取文本文件时出现以下错误。知道为什么吗?
输入:
This is a test.
A test, with tabs and too many spaces.
If this is a good one,
then all will be well.
输出:
then all will be well. too many spaces.
代码:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
string line;
ifstream infile ("A5.txt");
if (infile.is_open()) {
while (!infile.eof()) {
getline(infile,line);
cout << line << endl;
}
infile.close();
}
return 0;
}
【问题讨论】:
-
丢失
while(!infile.eof())构造。它也被称为“帕斯卡病”。在 C/C++ 中,在您读取 过去 文件末尾之前,eof() 是 not true,因此您将调用 getline() one too many i> 次。while( getline( infile, line ) )是编写此类循环的惯用正确方法。 -
我第二个@arayq2 的评论,进一步说鉴于 this 程序的构造,你也可以失去
if (infile.is_open())并简单地直接从ifstream infile ("A5.txt");移动到while( getline( infile, line ) )循环。