【问题标题】:Why does parse_config_file set failbit on a stream?为什么 parse_config_file 在流上设置故障位?
【发布时间】:2019-10-28 04:37:12
【问题描述】:

这个最小程序使用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 之前已经读取了流,为什么还要设置故障位?

【问题讨论】:

    标签: c++ stream boost-program-options


    【解决方案1】:

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

    尝试在文件结尾读取的操作失败,因此 eofbit 和 failbit 最终都被设置。该函数可用于检查失败是由于到达文件结尾还是其他原因。

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

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2020-06-05
      • 2016-03-24
      • 2021-05-02
      • 1970-01-01
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多