gpt4 book ai didi

c++ - boost spirit : how to collect "anything from line till particular word" into one variable?

转载 作者:搜寻专家 更新时间:2023-10-31 01:04:04 25 4
gpt4 key购买 nike

我有以下字符串

   GOOSE BAY  LATITUDE   53.27    LONGITUDE   299.60    ALTITUDE    46 M

我需要使用 Boost spirit 解析变量。

目前我有一段代码如下:

 qi::rule < string::const_iterator, std::string(), asc::space_type> any_string;
any_string %= as_string [lexeme[+(asc::char_ - asc::space)]];
r = phrase_parse(first, last,
(any_string[ph::ref(station) = _1] >> "LATITUDE" >>
double_[ph::ref(lat) = _1] >> "LONGITUDE" >> double_[ph::ref(lon) = _1] >>
"ALTITUDE" >> double_[ph::ref(alt) = _1] >> "M"), asc::space);

工作正常(即存储stationlatlon , alt 变量)如果在“纬度”之前我只有一个词。

但是,我还需要将“纬度”之前的任何内容存储到变量station 中,它应该是一个或几个(不只是两个,如示例)单词。但它不能使用“纬度”字样后的任何内容,因此纬度等仍会使用它们自己的变量。请帮助我找出正确的 Boost Spirit 表达式,以将行中看到的所有内容识别到 station,包括空格,直到特殊词(上例中的 LATITUDE) ).

最佳答案

注意事项:

  • asc::graph 等同于 asc::char_ - asc::space
  • lexeme 如果您在没有 skipper 的情况下声明规则(另请参见 Boost spirit skipper issues)

     qi::rule<It> any_string = +qi::graph_;
  • 只是断言第一个字段中每个字符的第一个关键字的否定匹配:

    +(qi::char_ - "LATITUDE")
  • 您可以传递对 phrase_parse API 的引用,这样您就可以不用语义操作(另请参阅 Boost Spirit: "Semantic actions are evil"?):

    bool r = qi::phrase_parse(first, last,
    ( qi::raw [ +(qi::char_ - "LATITUDE") ] >> "LATITUDE" >>
    qi::double_ >> "LONGITUDE" >>
    qi::double_ >> "ALTITUDE" >>
    qi::double_ >> "M"),
    asc::space,
    name, lat, lon, alt);

查看 Live On Coliru

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

namespace qi = boost::spirit::qi;
namespace asc= boost::spirit::ascii;

int main()
{
typedef std::string::const_iterator It;

std::string const input("GOOSE BAY LATITUDE 53.27 LONGITUDE 299.60 ALTITUDE 46 M");

std::string name;
double lat, lon, alt;

It first(input.begin()), last(input.end());

bool r = qi::phrase_parse(first, last,
(qi::raw [ +(qi::char_ - "LATITUDE") ] >> "LATITUDE" >>
qi::double_ >> "LONGITUDE" >>
qi::double_ >> "ALTITUDE" >>
qi::double_ >> "M"),
asc::space,
name, lat, lon, alt);

if (r)
std::cout << "Parsed: '" << name << "' lat:" << lat << " lon:" << lon << " alt:" << alt << "\n";
else
std::cout << "Failed\n";

if (first != last)
std::cout << "Remaining input: '" << std::string(first, last) << "'\n";
}

关于c++ - boost spirit : how to collect "anything from line till particular word" into one variable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24619152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com