Working with stringstreams?

Hey all,

I'm not exactly sure how to work with sringstreams. I thought it'd work just like an IO stream, but I'm encountering this weird problem. Say I read in lines from a txt file and load it on to the stringstream, shouldn't I then be able to extract from the stringstream onto some other variable?

Say the file "data.txt" looks like this:
1
2
3
4
5
6
1
500
500
2
0.5
0.5


And the program looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
int a;
std::string line;
std::stringstream ss (std::stringstream::in | std::stringstream::out);
std::ifstream file ("data.txt");
if (file.is_open())
{		
     std::getline (file,line);
     ss << line;
     std::cout << line <<"\n";
     ss >> a;
     std::cout << a << "\n";
}


When the contents of 'line' are printed, it accurately shows 1. But then when I supposedly extract it from the stringstream onto the int 'a' and print out 'a', I get the largest possible negative number for an int. I tried looking at the reference for stringstream, but I can't figure out what I'm doing wrong (it's probably something really stupid).

Thanks so much in advance!
I'm not sure why that isn't working but I have always used ss.str(line); instead of stream insertion.
That still doesn't seem to work. The problem seems to be that whenever I try to extract from the stringstream onto a variable, it just doesn't go through if the variable had some value before. Like if a = 2, then when I use ss >> a, a will remain 2 no matter what value was in the string stream.
Last edited on
Sorry for double posting, but it seems that it actually has to do with extracting twice from the string stream.

I can extract once, but then every subsequent extraction just gives me gibberish. Why?
Because you only get the first line with getline... You could just extract directly from the file, you know, it works the same way.
Wow, I'm an idiot. Yep, that's much cleaner and it actually works. Thanks!
Topic archived. No new replies allowed.