eof problem c++

eof problem c++

本文关键字:c++ problem eof      更新时间:2023-10-16

我在windows xp上使用Dev c++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
    string STRING;
    ifstream infile;
    infile.open ("sample.txt");
        while(!infile.eof)
        {
            getline(infile,STRING); 
            cout<<STRING; 
        }
    infile.close();
    return 0;
}

此代码给出以下错误

C:C++read.cpp: In function `int main()':
C:C++read.cpp:11: error: could not convert `infile.std::basic_ios<_CharT, _Traits>::eof [with _CharT = char, _Traits = std::char_traits<char>]' to `bool'
C:C++read.cpp:11: error: in argument to unary !

我不知道这里有什么问题,我不能编译代码请帮助

如果你将循环设置为

  while(getline(infile,STRING))
  {
     cout<<STRING; 
  }

可以避免读取最后一个值两次的可能性(参见这篇文章)。

std::ifstream::eof是一个返回bool值的函数。所以你必须把它命名为

infile.eof()

您在eof后面忘记了()