开发者

boost spirit to parse a structure

开发者 https://www.devze.com 2023-03-18 05:46 出处:网络
I would like to use boost::spirit to parse a structure from a std::string. In my example the string looks like what will be read from a file

I would like to use boost::spirit to parse a structure from a std::string. In my example the string looks like what will be read from a file

Do you know why it is not parsed at all? I copied the classic employee example but the string is not parsed.

AFG

std::string temp_1 = 
"MyStruct   {               \n"
"   a ""A"",            \n"
"   b ""B"",            \n"
"   c ""C"",            \n"
"   d ""D""             \n"
"  }                    \n"
;




namespace client{
    namespace qi = boost::spirit::qi;
    namespace ascii = boost::spirit::ascii;
    struct MyStruct{
        std::string a;
        std::string b;
        std::string c;
        std::string d;
    };
};



BOOST_FUSION_ADAPT_STRUCT(
    client::MyStruct,
    (std::string, a)
    (std::string, b)
    (std::string, c)
    (std::string, d)
)

namespace client
{
    template <typename Iterator>
    struct MyStruct_parser : qi::grammar<Iterator, MyStruct(), ascii::space_type>
    {
        MyStruct_parser() : MyStruct_parser::base_type(start)
        {
                using qi::lexeme;
                using ascii::char_;
            using qi::lit;

                quoted_string %= lexeme['"' >> +(char_ - '"') >> '"'];

                start %=
                lit("MyStruct")
                >> '{'
                >> "a" >> quoted_string >> ','
                >> "b" >> quoted_string >> ','
                >> "c" >> quoted_string >> ','
                开发者_StackOverflow社区>> "d" >> quoted_string
                >>  '}'
                ;
        }

        qi::rule<Iterator, std::string(), ascii::space_type> quoted_string;
        qi::rule<Iterator, MyStruct(),  ascii::space_type> start;
    };
}


int main( int argc, char** argv ){



    using boost::spirit::ascii::space;
    typedef std::string::const_iterator iterator_type;
    typedef client::MyStruct_parser<iterator_type> MyStruct_parser;

    std::stringstream inp(temp_1);

    std::string line;
    while( std::getline( line, inp ) ){

        std::string::const_iterator a = line.begin();
            std::string::const_iterator b = line.end();

        MyStruct_parser g; // Our grammar
        client::MyStruct obj;
        bool r = phrase_parse( a, b, g, space, obj);
        if( r ){
            std::cout << "parsed" << std::endl;
        }else{
            std::cout << "not parsed" << std::endl;
        }
    }
    return 1;
}


It seems your strings in temp_1 arn't quoted, but your grammar expects quoted strings. To add a quote to string literal, use escape \"


If you write your input data as:

std::string temp_1 = 
"MyStruct   {\n"
"   a \"A\",\n"
"   b \"B\",\n"
"   c \"C\",\n"
"   d \"D\"\n"
"  }\n"
;

(i.e. add proper quoting) it will work.

0

精彩评论

暂无评论...
验证码 换一张
取 消