I have been playing around with parsing with Boost Spirit and was wondering if anyone could help me get this to work. I have a simple parser that takes a file containing a pair of entries on each line. Something similar to the following:
Foo 04B
Bar 1CE
Bam 456
My code below currently parses this out and places each pair into a std::map and it seems to work correctly. What I really want to do is parse out the second string on each line and convert it to an integer. I have looked at int_parser and how you can specify the base but have been unable to get a similar setup to compile.
namespace qi = boost::spirit::qi;
std::map<std::string, std::string> results;
void insert(std::pair<std::string, std::string> p) {
results[p.first] = p.second;
}
template <typename Iterator>
bool parse_numbers(Iterator first, Iterator last) {
using qi::char_;
using qi::parse;
qi::rule<Iterator, std::pair<std::string, std::string>()> assignment;
assignment = +(~char_(' ')) >> +(char_);
bool r = parse(
first,
last,
assignment[&insert]);
if (first != last)
return false;
return r;
}
int main(int argc, char* argv[]) {
std::ifstream ifs;
std::string str;
ifs.open (argv[1], std::ifstream::in);
while (getline(ifs, str)) {
if (!parse_numbers(str.begin(), str.end())) {
std::cout << "Parsing failed\n";
}
}
return 0;
}
What I would really like if to parse it out directly as a std::pair<std::string, int
>. Any help is appreciated.
More information:
I was trying to declare a parser similar to this one:
uint_parser<unsigned, 16> hex_value;
and then I was trying to replace the +(char_) in my rule to +(hex_value).