Assign default value to variable using boost spirit

后端 未结 2 2009
故里飘歌
故里飘歌 2021-01-22 03:22

Suppose I have the following string to parse:

\"1.2, 2.0, 3.9\"

and when I apply the following parser for it:

struct DataStruct
{
    dou         


        
2条回答
  •  野性不改
    2021-01-22 03:35

    You might use the following code:

    #include 
    #include 
    #include 
    #include 
    struct DataStruct
    {
        double n1, n2, n3;
    };
    
    BOOST_FUSION_ADAPT_STRUCT(DataStruct, (double, n1)(double, n2)(double, n3))
    
    int main() {
        using namespace boost::spirit;
    
        using Iterator = typename std::string::iterator;
    
        qi::rule reader_ = (qi::double_[_val = _1] | (lexeme["null"])[_val = 0.]);
    
        qi::rule data_ = reader_ >> ',' >> reader_ >> ',' >> reader_;
    
        try {
            DataStruct res;
            auto str = std::string("1.2,null,3.9");
            auto start = str.begin();
            auto end = str.end();
    
            bool ok = qi::parse(start, end, data_, res);
            if (ok) {
                std::cout << "parse completed" << std::endl;
            }
            else {
                std::cout << "parse failed" << std::endl;
            }
        }
        catch (const qi::expectation_failure& except) {
            std::cout << except.what();
        }
    
        std::cout << std::endl;
    }
    

提交回复
热议问题