gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 01:20:22 24 4
gpt4 key购买 nike

这个最小的程序使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com