2012-05-02 11 views
7

私はboost::spiritを勉強しようとしています。たとえば、一連の単語を解析してvector<string>にしようとしています。boost :: spiritを使用して一連の単語をベクトルに解析する方法は?

'thisisatest' 

が、私はそれぞれの単語が個別にマッチしている次の出力、望んでいた:

'this' 
'is' 
'a' 
'test' 

可能であれば、私は」を私にこの出力を与える

#include <boost/spirit/include/qi.hpp> 
#include <boost/foreach.hpp> 

namespace qi = boost::spirit::qi; 

int main() { 

    std::vector<std::string> words; 
    std::string input = "this is a test"; 

    bool result = qi::phrase_parse(
     input.begin(), input.end(), 
     +(+qi::char_), 
     qi::space, 
     words); 

    BOOST_FOREACH(std::string str, words) { 
    std::cout << "'" << str << "'" << std::endl; 
    } 
} 

:私はこれを試してみましたこの単純なケースのために私自身のサブクラスを定義する必要を避けるのが好きです。

答えて

13

あなたはスキップパーサとして使用スキップパーサ– qi::spaceを、根本的の目的を誤解(あるいは少なくとも誤用)している、a bab差がないことを空白にとらわれないように、あなたのパーサを作るためです。

あなたの場合、空白は、単語を区切りたいので、です。その結果、あなたは空白をスキップしてはならない、とあなたはqi::phrase_parseではなく、qi::parseを使用したい:

#include <vector> 
#include <string> 
#include <iostream> 
#include <boost/foreach.hpp> 
#include <boost/spirit/include/qi.hpp> 

int main() 
{ 
    namespace qi = boost::spirit::qi; 

    std::string const input = "this is a test"; 

    std::vector<std::string> words; 
    bool const result = qi::parse(
     input.begin(), input.end(), 
     +qi::alnum % +qi::space, 
     words 
    ); 

    BOOST_FOREACH(std::string const& str, words) 
    { 
     std::cout << '\'' << str << "'\n"; 
    } 
} 

が(今G. Civardiの修正で更新。)

+0

よく説明されています、+1 – sehe

2

私はこれが最小バージョンであると考えています。 qiリストに適用されたqi :: omitパーサーは不要です。出力属性は生成されません。詳細については以下を参照してください。そうでないhttp://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/reference/operator/list.html

#include <string> 
#include <iostream> 
#include <boost/foreach.hpp> 
#include <boost/spirit/include/qi.hpp> 

int main() 
{ 
    namespace qi = boost::spirit::qi; 

    std::string const input = "this is a test"; 

    std::vector<std::string> words; 
    bool const result = qi::parse(
     input.begin(), input.end(), 
     +qi::alnum % +qi::space, 
     words 
); 

    BOOST_FOREACH(std::string const& str, words) 
    { 
     std::cout << '\'' << str << "'\n"; 
    } 
} 
1

念の誰かが先頭のスペースの私の問題に遭遇します。

私はいくつかのスペースで始まる文字列を実行するまで、ildjarnのソリューションを使用していました。

std::string const input = " this is a test"; 

先頭のスペースが関数qi :: parse(...)の失敗につながることがわかりました。解決策は、qi :: parse()を呼び出す前に入力の先頭スペースをトリムすることです。

関連する問題