Boost logo

Boost :

Subject: [boost] [spirit]
From: Chandrashekhar Kumar (iitk.cs_at_[hidden])
Date: 2009-06-04 14:58:54


Hi,

I have to parse the file, the contents of which(with a header) is below and
stuff the double part only to std::vector<double>:

"A","B","C","D"
1,2,3,4
5,6.7,8
........

I started simple without header approach first :

from libs/spirit/example/lex/example.hpp:

inline std::string
read_from_file(char const* infile)
{
    std::ifstream instream(infile);
    if (!instream.is_open()) {
        std::cerr << "Couldn't open file: " << infile << std::endl;
        exit(-1);
    }
    instream.unsetf(std::ios::skipws); // No white space skipping!
    return std::string(std::istreambuf_iterator<char>(instream.rdbuf()),
                       std::istreambuf_iterator<char>());
}

from libs/spirit/classic/examples/number_list.hpp:

///////////////////////////////////////////////////////////////////////////////
//
// Our comma separated list parser
//
///////////////////////////////////////////////////////////////////////////////
bool
parse_numbers(char const* str, vector<double>& v)
{
    return parse(str,

        // Begin grammar
        (
            real_p[push_back_a(v)] >> *(',' >> real_p[push_back_a(v)])
        )
        ,
        // End grammar

        space_p).full;
}

int main()
{
    std::string str = read_from_file("test.csv");

    std::vector<double> v;

     if (parse_numbers(str.c_str(), v))
        {
            cout << "-------------------------\n";
            cout << "Parsing succeeded\n";
            cout << str << " Parses OK: " << endl;

            for (vector<double>::size_type i = 0; i < v.size(); ++i)
                cout << i << ": " << v[i] << endl;

            cout << "-------------------------\n";
        }
        else
        {
            cout << "-------------------------\n";
            cout << "Parsing failed\n";
            cout << "-------------------------\n";
        }
}

But after running it, I am getting the result as "Parsing failed".

I am going thru the doc to understand it better, but any quick spot will
help me immensely.

Thanks,
Chandra


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk