最后一行打印两次(C++)

Tho*_*mas 1 c++

我有一个名为scores.txt的文本文件,其中包含以下数据:

John T Smith 90
Eric K Jones 103
Ram S Krishnan 25
Marie A Bell 50
Run Code Online (Sandbox Code Playgroud)

我正在尝试从此文件中读取数据并使用以下C++代码进行打印:

ifstream input;
input.open("scores.txt");
string firstName;
char mi;
string lastName;
int score;

while (input) {
    input>>firstName>>mi>>lastName>>score;
    cout<<firstName<<" "<<mi<<" "<<lastName<<" "<<score<<endl;
}

input.close();
cout<<"Done"<<endl;
Run Code Online (Sandbox Code Playgroud)

输出是:

John T Smith 90
Eric K Jones 103
Ram S Krishnan 25
Marie A Bell 50
Marie A Bell 50
Run Code Online (Sandbox Code Playgroud)

为什么最后一行(Marie A Bell 50)被打印两次?我怎样才能防止这种情况发生?

YSC*_*YSC 6

这是因为刚刚读完文件的最后一行后,input还没有到文件末尾.你的程序while第五次进入循环,读取input(将其设置为文件结束状态),不改变你的变量并打印它们.

避免这种情况的一种方式(在众多中)就是写出类似的东西

while (input >> var1 >> var2)
{
    std::cout << var1 << "," << var2 << std::endl;
}
Run Code Online (Sandbox Code Playgroud)