Parse data from a string to a vector

Hi,

I'm trying to parse the data (of different types: double, char, int) from a string to a 1D vector. The string looks like this:
A: 12345 g 0.1234 0.5678

And I want my vector to look like this:
12345 g 0.5678

My current code is as follows:
1
2
3
4
5
6
if (0 == line.find("A:")) {
    stringstream ss1(line.substr(2,5));
    stringstream ss2(line.substr(7,1));
    stringstream ss3(line.substr(14));
    vector<cdata> data(ss1, ss2, ss3); 
}


This gives me a list of allocation errors.
What should I do?

Any help would be greatly appreciated!
Last edited on
closed account (DSLq5Di1)
I don't imagine initializing a vector with 3 stringstreams would work too well..
http://www.cplusplus.com/reference/stl/vector/vector/

1
2
3
4
5
6
struct cdata
{
    int a;
    char b;
    double c, d;
};

1
2
3
4
5
6
7
8
9
10
11
vector<cdata> data;

if (0 == line.find("A:"))
{
    stringstream ss(line.substr(2));

    cdata tmp;
    ss >> tmp.a >> tmp.b >> tmp.c >> tmp.d;

    data.push_back(tmp);
}
Thank you. But what if I only want tmp.a, tmp.b and tmp.d in data? Will I write:
 
ss >> tmp.a >> tmp.b >> tmp.d;

instead? Will this work when line.substr only takes everything after the second character?
closed account (DSLq5Di1)
>> extracts the next value delimited by whitespace. If you want to skip over your 3rd field you could do:-

ss >> tmp.a >> tmp.b >> tmp.d >> tmp.d;

or

#include <limits>

1
2
3
ss >> tmp.a >> tmp.b;
ss.ignore().ignore(numeric_limits<streamsize>::max(), ' ');
ss >> tmp.d;
I chose the first method. However, this is the error I get:

no matching function for call to 'std::vector<cdata>::push_back(ChallengeData::read_from_file(std::string)::cdata&)'
c:\mingw\bin\../lib/gcc/mingw32/4.5.2/include/c++/bits/stl_vector.h:741:7: note: candidate is: void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = cdata, _Alloc = std::allocator<cdata>, value_type = cdata]

What does this error mean? I'm using Eclipse and the error is at the data.push_back(tmp) line.
closed account (DSLq5Di1)
Could you post what you have? http://ideone.com/
It's fixed now... Thank you for helping me!
Topic archived. No new replies allowed.