提升精神来解析一个结构

时间:2011-07-06 16:09:00

标签: c++ parsing boost-spirit

我想使用boost::spirit来解析std::string中的结构。在我的示例中,字符串看起来像将从文件中读取

你知道为什么它根本没被解析吗?我复制了经典employee示例,但未解析字符串。

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 >> ','
                >> "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;
}

2 个答案:

答案 0 :(得分:3)

似乎你的temp_1中的字符串没有被引用,但是你的语法需要引用字符串。要向字符串文字添加引号,请使用escape \“

答案 1 :(得分:3)

如果您将输入数据写为:

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

(即加上适当的引语)它会起作用。