I was trying to use boost-spirit to parse a fairly simple cvs file format.
My csv file looks like this:
Test.txt
2
5. 3. 2.
6. 3. 6.
The first integer represents the number of lines to read and each line consists of exactly three double values.
This is what I got so far.
main.cpp
#include <vector>
#include <fstream>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_stl.hpp>
#include <boost/phoenix/object/construct.hpp>
std::vector<std::vector<double>> parseFile(std::string& content)
{
std::vector<std::vector<double>> ret;
using namespace boost::phoenix;
using namespace boost::spirit::qi;
using ascii::space;
int no;
phrase_parse(content.begin(), content.end(),
int_[ref(no) = _1] >> repeat(ref(no))[(double_ >> double_ >> double_)[
std::cout << _1 << _2 << _3
]], space
);
return ret;
}
int main(int arg, char **args) {
auto ifs = std::ifstream("Test.txt");
std::string content((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>()));
parseFile(content);
}
Now instead of the line std::cout << _1 << _2 << _3 I'm need of something that appends a std::vector<double> containing the three values.
I already tried _val=construct<std::vector<double>>({_1,_2,_3}), but it is not working. So what I'm doing wrong?
It's much simpler than you think¹
See it Live On Coliru. It uses automatic attribute propagation - the single most useful feature of Spirit to begin with - and the
blankskipper instead ofspaceso we can still parseeolNow, I'd suggest to make it even simpler:
Live On Coliru
Or, in fact, even simpler using just the standard library:
Live On Coliru
All of them successfully parsing and printing:
¹ Boost Spirit: "Semantic actions are evil"?
Bonus Take: Auto Custom Attribute Types
Instead of opaque vectors, why don't you use a struct like
And parse into a
std::vector<Point>. As a bonus you get output and parser basically for free:See it Live On Coliru