Effective data analysis of std :: stringstream in std :: vector <std :: vector <double>>

I am parsing the data stream of pairs of double values ​​in std :: vector>. I use boost as I think it is more efficient. My code is as follows.

                std::stringstream tmp_stream;                
                typedef double data_type;            
                typedef ::std::vector < data_type > V_d;
                // type below describes type of the container of all data
                typedef ::std::vector < V_d > V_v_d;
                // list container 
                //typedef ::std::list < V_d > V_v_d;

                V_v_d data;

                ::data_parser::Data_parser < V_v_d > data_parser;
                data_parser ( tmp_stream, data );

My input text file is formatted as {(132.181,0.683431), (136.886,0.988517), (137.316,0.504297), (133.653,0.602269), (150.86,0.236839)} The pair is not processed correctly, and I received an empty pair. What could be the problem? Thanks

+3
source share
1 answer

Using the Boost Spirit bit, you can use one line:

if (tmp_stream >> std::noskipws >> 
       qi::phrase_match((+qi::double_) % qi::eol, qi::blank, data))
{

and another line to display the results as a bonus:

    std::cout << karma::format((karma::double_ % ", ") % karma::eol, data) << "\n";
}

Note . It handles inf, -inf, nan:)

Live on Coliru:

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

namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;

int main()
{
    std::vector<std::vector<double>> data;

    std::stringstream tmp_stream(
            "123 45 inf -inf nan .7e-99\n"
            "42\n"
            "-1");

    if (tmp_stream >> std::noskipws >> qi::phrase_match((+qi::double_) % qi::eol, qi::blank, data))
    {
        std::cout << karma::format((karma::double_ % ", ") % karma::eol, data) << "\n";
    }
}

UPDATE , :

#include <boost/fusion/adapted/std_pair.hpp> // handle std::pair
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/karma.hpp>
#include <boost/spirit/include/qi_match.hpp>

namespace qi = boost::spirit::qi;
namespace karma = boost::spirit::karma;

int main()
{
    std::vector<std::pair<double, double>> data;

    std::stringstream tmp_stream("{ (132.181,0.683431), (136.886,0.988517), (137.316,0.504297), (133.653,0.602269), (150.86,0.236839) }");

    if (tmp_stream >> std::noskipws >> qi::phrase_match(
                   '{' 
                >> 
                     ( '(' >> qi::double_ >> "," >> qi::double_ >> ')' )
                     % ','
                >> '}',
                qi::space, data))
    {
        std::cout << karma::format(karma::delimit(" ") [karma::auto_] % karma::eol, data) << "\n";
    }
}

: (. Live On Coliru

132.181 0.683 
136.886 0.989 
137.316 0.504 
133.653 0.602 
150.86 0.237 

, ,

  • streambuf_iterator
  • ,
+5

All Articles