1

当这段代码完成时,为什么我会得到一个额外的迭代(打印额外的行)?EOF 是否需要额外的换行符?我宁愿不必添加额外/特殊字符来标记 EOF。

#include <iostream>  
#include <fstream>  
#include <string>  
using namespace std;  

int main(){  
    ifstream infile("dictionary.txt"); // one word per line  
    string text;  
    while(infile){  
        infile >> text;  
        cout << text << endl;  
    }  
    infile.close();  
    return 0;  
}  
4

5 回答 5

6

尝试

while(infile>>text) cout << text << endl;

反而。

于 2009-10-06T20:38:23.593 回答
6

直到您尝试读取它之后,输入流才会检测到文件结尾。当您读取文件中的最后一个单词时,输入流仍然有效;在下一个循环中,infile >> text尝试读取过去的 EOF 并失败,但下一行仍会执行。

循环应如下所示:

while (infile >> text)
    cout << text << endl;

这样,EOF 将在尝试写入输出之前被检测到。

于 2009-10-06T20:42:28.203 回答
3

使用您的 while 条件检查流是否处于良好状态。然后你从流中读取,这可能会也可能不会成功。然后你输出文本的值。你应该做的是:

while(infile >> text){
    cout << text << endl;
}
于 2009-10-06T20:40:53.557 回答
3

在文件的末尾,infile可能仍会评估为true,但以下提取的单词infile >> text失败。即使它失败了,你仍然会打印出一行。更好的方法是让 while 循环检查是否成功提取:

string text;
ifstream infile("dictionary.txt"); // one word per line  
while (infile >> text) {
    cout << text << endl;  
}
infile.close();
于 2009-10-06T20:41:19.313 回答
1

您已经得到了一些更正,但也许有一点不同的更正值得考虑:

#include <iterator>
#include <iostream>
#include <string>
#include <fstream>

using namespace std; // not really a good idea, but harmless enough for now.

int main() { 
    ifstream infile("dictionary.txt");
    copy(istream_iterator<string>(infile), istream_iterator<string>(), 
        ostream_iterator<string>(cout, "\n"));
    return 0;
}
于 2009-10-06T21:23:43.563 回答