开发者

Parse string to int or float with boost spirit

开发者 https://www.devze.com 2023-03-29 09:07 出处:网络
I need to parse a wstring to int, float or a string itself. I found a question similar to mine Here but I don\'t understand how to use the parser. I don\'t fin开发者_开发百科d the test_parser method.

I need to parse a wstring to int, float or a string itself. I found a question similar to mine Here but I don't understand how to use the parser. I don't fin开发者_开发百科d the test_parser method. The question is: after implementing the custom rules for the parser, how to use them?


Parsing a wstring to an int is straight forward:

wstring str(L"1234");
int i = 0;
qi::parse(str.begin(), str.end(), qi::int_, i);
assert(i == 1234);

Similarily, parsing a float looks like:

wstring str(L"1234.567");
double d = 0;
qi::parse(str.begin(), str.end(), qi::double_, d);
assert(d == 1234.567);

I'm not sure what you mean by 'parsing a string'. If you mean it as parsing a quoted string you could write it as:

wstring str(L"\"abc\"");
wstring s;
qi::parse(str.begin(), str.end(), '"' >> *~qi::char_('"') >> '"', s);
assert(s == L"abc");

the expession '"' >> *~qi::char_('"') >> '"' means: a quote ('"') followed by (>>) zero or more (*) characters which are not a quote (~qi::char_('"')) followed by (>>) another quote ('"') .

0

精彩评论

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

关注公众号