【问题标题】:why istream::get sets failbit and eofbit together?为什么 istream::get 将 failbit 和 eofbit 设置在一起?
【发布时间】:2015-05-12 21:08:48
【问题描述】:

我想知道为什么 istream::get 将 failbit 和 eofbit 设置在一起。

std::getline 的行为不同:它在遇到文件末尾时设置 eofbit,当您尝试读取文件末尾时设置失败位。所以你可以写:

while (std::getline(is, s) {
  blablabla... // gets executed once after end of file has been reached
}

而如果您使用 std::get 定义自己的 getSthg 函数

std::istream& myOwnGetLine(std::istream& is, std::string& s) {
  char c;
  while (is.get(c)) {
    blablabla...
  }
  return is;
}

然后:

while (myOwnGetLine(is, s)) { // fails if eof has been reached
  blablabla // won't get executed for the last line of the stream
}

那么:我做错了什么?我想出的解决方法是:

std::istream& myOwnGetLine(std::istream& is, std::string& s) {
  *if (is.rdstate() & std::ios::eofbit) { 
    is.clear(std::ios::failbit);
    return is;
  }*  
  char c;
  while (is.get(c)) {
    blablabla...
  }
  *if (is.rdstate() & std::ios::eofbit) {
    is.clear(std::ios::eofbit);
  }*
  return is;
}

但这听起来不对……

【问题讨论】:

    标签: c++ get eof istream


    【解决方案1】:

    不幸的是,使用istream::get 来创建getline 函数会导致该函数内部出现一些尴尬的代码,因为根据规范,它会在到达文件结尾时同时设置eofbitfailbit。标准istream::getline 解决此问题的方式是使用istreamrdbuf() 来检查值。看起来这可能是解决这个问题的唯一方法(除了操纵流的失败状态)

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2012-02-29
      • 2012-11-19
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 2018-03-05
      • 2014-05-09
      • 1970-01-01
      相关资源
      最近更新 更多