ifstream::eof在if语句中时抛出类型错误

ifstream::eof throws a type error when in if statement

本文关键字:错误 类型 语句 eof if ifstream      更新时间:2023-10-16

我有一个类a,它有一个std::ifstream filestr成员。在其中一个类函数中,我测试流是否已达到eof。

class A
{
private:
   std::ifstream filestr;
public:
   int CalcA(unsigned int *top);  
}

然后在cpp文件中,我有

int CalcA(unsigned int *top)
{
   int error;
   while(true)
   {
      (this->filestr).read(buffer, bufLength);
      if((this->filestr).eof);
      {
         error = 1;
         break;
      }
   }
   return error;
}

我得到一个编译错误

error: argument of type ‘bool (std::basic_ios<char>::)()const’ does not match ‘bool’

有人能告诉我如何正确使用eof吗?或者我出现这个错误的其他原因?

eof是一个函数,因此需要像其他函数一样调用:eof()

也就是说,给定的读取循环可以在不调用eof()的情况下更正确地写入(考虑文件结尾以外的其他故障可能性),但将读取操作转换为循环条件:

while(filestr.read(buffer, bufLength)) {
    // I hope there's more to this :)
};

尝试

if(this->filestr).eof())

(this->filestr).eof单独是指向成员方法的指针。if语句需要bool类型的表达式。因此,您需要调用该方法。这将成功,因为它返回一个bool值。

(this->filestr).eof没有调用该函数。(this->filestr).eof()是.:-)这解释了您的错误。