c++ - boost qi::phrase_parse 只读取第一个元素

标签 c++ boost boost-spirit-qi

我已经使用 boost::spirit 实现了简单的 ascii 解析器. 目标 ascii 文件看起来像

n

0 23 45 10.0 0.5

.....

n-1 x y .....

但它在 measure_list 中只返回 1 个元素

如果我试图将 ASCII 阅读为简单的 vector<double>例如,而不是结构化 - 它工作正常。怎么了?

struct measure
{
   int id;
   double x, y, size_, angle;
} 

BOOST_FUSION_ADAPT_STRUCT(measure, (int, id)(double, x)(double, y)(double, size_)(double, angel))

typedef std::vector<measure> data_t;

void RelativeMeasure(string filename)
        {
                clear();

                if(!filesystem::exists(filename)) return;

                file_name = filename;



                ifstream calibration_file(filename);

                if(calibration_file.is_open())
                {
                        int key_count;
                        calibration_file >> key_count;

                        istreambuf_iterator<char> eos;
                        istreambuf_iterator<char> it(calibration_file);

                        std::string strver(it, eos);

                        std::vector<measure> measure_list;
                        measure_list.reserve(100000);

                        qi::phrase_parse(strver.begin(), strver.end(), (qi::int_ > qi::double_ > qi::double_ > qi::double_ > qi::double_) % qi::eol, qi::blank, measure_list);

                        for each(auto measure in measure_list) key_list.push_back(KeyPoint(measure.x, measure.y, measure.size_, measure.angel));
}

最佳答案

我看到的最有可能的罪魁祸首是您没有吃掉 n 之后的换行符。或许还可以使用 +qi::eol 作为分隔符。

但这并不能说明您阅读了第一个条目。

您可以通过使用流式 API(在后台使用 boost::spirit::istream_iterator 多 channel 适配器)来简化事情:

Live On Coliru

void RelativeMeasure(std::string filename)
{
    std::ifstream calfile(filename, std::ios::binary);

    int key_count;
    std::vector<measure> measure_list;

    using namespace qi;
    if (
        calfile >> std::noskipws >> phrase_match(int_, blank, key_count)
        && calfile >> phrase_match(qi::repeat(key_count)[int_ > double_ > double_ > double_ > double_ > +eol], blank, measure_list)
    )
    {
        std::vector<KeyPoint> key_list;
        key_list.reserve(measure_list.size());
        // using a converting constructor (why not parse into this at once?)
        std::copy(measure_list.begin(), measure_list.end(), back_inserter(key_list));
    }
}

关于c++ - boost qi::phrase_parse 只读取第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29883279/

相关文章:

c++ - 单击按钮时 Visual C++ 打开对话框

c++ - 在公共(public)接口(interface)中使用共享指针

c++ - 如何通过标准元组操作正确转发和使用 constexpr 结构的嵌套元组

c++ - 为什么在单例实现中清除 boost::scoped_ptr

c++ - 命名空间 'vsnprintf' 中没有名为 'std' 的成员;你是说 'vsprintf' 吗?

c++ - 未解析的外部符号虽然它已经被定义

c++ - 对于具有单个接受器的线程化 boost::asio 服务器,我们是否需要每个线程多个 io_service

c++ - 一位数字的 boost Spirit 解析器出现段错误

c++ - 是否可以在另一个语法定义中重用 boost::spirit::qi 语法?

c++ - 使用 Boost Spirit 2 解析字符串以在用户定义的结构中填充数据