为什么会出现空白?

时间:2015-12-08 18:52:29

标签: c++

我有以下C ++程序:

ofstream output("scores.txt");
output<<"John"<<" "<<"T"<<" "<<"Smith"<<" "<<90<<endl;
output<<"Eric"<<" "<<"K"<<" "<<"Jones"<<" "<<103<<endl;
output.close();

ifstream input;
input.open("scores.txt");
string line;
while (!input.eof()) {
    getline(input, line);
    cout<<line<<endl;
}
input.close();

cout<<"Done";

输出结果为:

John T Smith 90
Eric K Jones 103

Done

为什么Eric K Jones 103和Done之间有空白?

1 个答案:

答案 0 :(得分:0)

Structure your loop like this:

while (getline(input, line)) {
    cout<<line<<endl;
}

Your duplicate line is because the way your read loop is structured, once you read the last line the eof bit is not set yet because readline succeeded. Therefore, you iterate one more time, doing a readline that does set the eof bit, then you do cout<<line<<endl and that last endl is your extra blank line.