C++ 文件末尾的重复值

C++ 文件末尾的重复值,c++,file-io,ifstream,C++,File Io,Ifstream,我正在编写一个程序,从文件中获取输入并在控制台上显示。问题是最后一个条目重复了两次。代码如下:- int main(void) { string filename; int grades; cout<<"Enter the filename:"<<endl; getline(cin,filename); ifstream inFile(filename.c_str(),ios::in); if(!inFile){

我正在编写一个程序,从文件中获取输入并在控制台上显示。问题是最后一个条目重复了两次。代码如下:-

int main(void)
{
    string filename;
    int grades;
    cout<<"Enter the filename:"<<endl;
    getline(cin,filename);
    ifstream inFile(filename.c_str(),ios::in);
    if(!inFile){
        cout<<"File does not exist."<<endl;
        exit(1);
    }
    while(!inFile.eof())
    {
        inFile>>grades;
        cout<<grades<<endl;
    }
    inFile.close();
    return 0;
}
int main(无效)
{
字符串文件名;
国际职系;
这是错误的

while(!inFile.eof())
    {
        inFile>>grades;
        cout<<grades<<endl;
    }
while(!infle.eof())
{
填充>>等级;

语法上正确,是的。但逻辑上不正确。你正在使用
eof()
错误

首先要认识到的是 测试状态基于最后一次输入的结果。并且您必须 在使用任何东西之前,请始终检查输入是否成功 您已输入;当您写入时:

inFile >> grades;
std::cout << grades;
从软件工程的角度来看,这太可怕了 (在
while
的条件下修改状态),但是 它无处不在,任何其他东西都会引起疑问

如果由于任何原因出现输入错误,此操作将停止。一次 你已经看到了失败(只有到那时),你才能问为什么:

if ( inFile.bad() ) {
    //  Serious hardware failure...
} else if ( !inFile.eof() ) {
    //  Format error in the input...
} else {
    //  Normally, no more data in the input stream, but
    //  there are a few special cases where you could still
    //  have a format error and end up here.  Not with
    //  `int`, however.
}

但同样,这只有在输入失败后才有效。

已经有几十篇文章在发表了,所以,请再次执行一次搜索
while(infle>>grades)
:不要使用
while(!infle.eof())
。不要使用
while(infle.good())
也可以。看,真正的问题是他从哪里得到这个成语。任何使用这个成语的网站或书籍都对垃圾桶有好处,其他什么都没有。它不会告诉你最后一次阅读是否失败。是否
eof()
在成功读取后返回true或not取决于您正在读取的内容以及您在输入序列中的位置。您可以说,如果
eof()
返回true,则下一次读取将失败(但如果返回false,则下一次读取也可能失败)。如果
fail()
返回true,则
eof()
是真的,很有可能(但不是100%)失败的原因是我们在读取值之前到达了文件末尾。关于您的最后一句话:
eof()没有合理的使用
在您通过其他方式检测到故障之前。它的唯一用途是尝试确定故障原因,即
fail()&&!eof()
表示您在输入中有格式错误。
while ( inFile >> grades ) {
    std::cout << grades << std::endl;
}
if ( inFile.bad() ) {
    //  Serious hardware failure...
} else if ( !inFile.eof() ) {
    //  Format error in the input...
} else {
    //  Normally, no more data in the input stream, but
    //  there are a few special cases where you could still
    //  have a format error and end up here.  Not with
    //  `int`, however.
}