c++ - 为什么 parse_config_file 在流上设置 failbit?

标签 c++ stream boost-program-options

这个最小的程序使用 boost::program_options 来解析 stringstream。奇怪的是,在解析之后,流不再处于“良好”状态,并且设置了 failbit 和 eofbit。

#include <iostream>
#include <sstream>
#include <boost/program_options/options_description.hpp>
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>

void test_stream(std::stringstream& s);

int main()
{
  using namespace std;
  namespace po = boost::program_options;

  stringstream s;
  s << "seed=3" << '\n';
  test_stream(s);

  po::options_description desc("");
  desc.add_options()
    ("seed", po::value<int>());
  po::variables_map vm;
  po::store(po::parse_config_file(s, desc, true), vm);
  po::notify(vm);

  test_stream(s);

  return 0;
}

void test_stream(std::stringstream& s)
{
  using namespace std;

  if (s.good())
    {
      cout << "stream is good" << endl;
    }
  else
    {
      cout << "stream is not good" << endl;
      if (s.rdstate() & ios_base::badbit)
    cout << "badbit is set" << endl;
      if (s.rdstate() & ios_base::failbit)
    cout << "failbit is set" << endl;
      if (s.rdstate() & ios_base::eofbit)
    cout << "eofbit is set" << endl;
    }
}

输出:

stream is good
stream is not good
failbit is set
eofbit is set

虽然 eof 条件在某种程度上是预期的,但由于推测解析器已读取流直到 EOF,为什么还设置了 failbit?

最佳答案

根据 ios::eof 的文档标记在某些情况下可能会发生这种情况:

Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.

Boost 的解析器使用 std::copy() 和流上的迭代器来提取选项。正如 Jerry Coffin's answer 中指出的那样对于另一个问题,迭代器从序列中读取项目。读取最后一个后,序列的 eof 位被设置。当迭代器再次递增以获得流结束迭代器时,这是在 copy() 中离开循环的条件,它会尝试再次读取,因此也是流的 设置失败位。

关于c++ - 为什么 parse_config_file 在流上设置 failbit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56582946/

相关文章:

c++ - Windows下设置Netbeans编译wxWidgets项目

c++ - QT 以普通用户身份启动程序

java - 当我可以使用后者创建文件时,为什么我应该创建 File 对象,然后在 FileWriter 或 PrintWriter 中使用它?

node.js - Nodejs 可读流推送使用

c++ - 使用 boost::program_options 作为类的静态成员

c++ - 从 16 位 PCM 中去除 C++ 中的音频噪声(嘶嘶声)

c++ - 为什么要分配一个比请求大小大 1 的数组?

javascript - 如何在 Nodejs 流中正确处理异步操作

c++ - boost 程序选项在从命令行读取时更改数据(这是 boost 中的错误吗?)

boost::program_options :当属于命名空间时如何声明和验证我自己的选项类型?