extracting data from string streams

D

Dylan

I'm attempting to write an object's state to a std::stringstream and
then to restore that state by reading from the stringstream. The
writing is fine but I'm having problems reading. Here's a little prog
that demonstrates the problem:

#include <iostream>
#include <sstream>

int main()
{
//create a buffer containing "1,2,3"
std::stringstream ss;
ss << 1 << "," << 2 << "," << 3;
std::cout << "\n" << ss.str();

//I'd like to assign 1 to iVal1 and 2 to iVal2, leaving ",3" in ss
//(but the following doesn't work)
int iVal1, iVal2;
ss >> iVal1 >> iVal2;
std::cout << "\n" << iVal1 << "," << iVal2;
std::cout << "\n" << ss.str();

return 0;
}

//The output from this is
1,2,3
1, -858993460
1,2,3

//but I'd like it to be
1,2,3
1,2
3,

How can i achieve this?

Thanks!
 
M

Maxim Yegorushkin

Dylan said:
I'm attempting to write an object's state to a std::stringstream and
then to restore that state by reading from the stringstream. The
writing is fine but I'm having problems reading. Here's a little prog
that demonstrates the problem:

#include <iostream>
#include <sstream>

int main()
{
//create a buffer containing "1,2,3"
std::stringstream ss;
ss << 1 << "," << 2 << "," << 3;
std::cout << "\n" << ss.str();

//I'd like to assign 1 to iVal1 and 2 to iVal2, leaving ",3" in ss
//(but the following doesn't work)
int iVal1, iVal2;
ss >> iVal1 >> iVal2;
std::cout << "\n" << iVal1 << "," << iVal2;
std::cout << "\n" << ss.str();

return 0;
}

//The output from this is
1,2,3
1, -858993460
1,2,3

//but I'd like it to be
1,2,3
1,2
3,

How can i achieve this?

Standart streams use whitespaces as delimeters. To achive what you want
use spaces or tabs instead of commas when outputting.
 
D

Dylan

Standart streams use whitespaces as delimeters. To achive what you want
use spaces or tabs instead of commas when outputting.

ok, thanks. That helps partly, but using the >> operator doesn't
remove the values from the stream. Do you know how I can remove
values?
 
M

Maxim Yegorushkin

Dylan said:
ok, thanks. That helps partly, but using the >> operator doesn't
remove the values from the stream. Do you know how I can remove
values?

operator>> does not change the buffer, but it does move the buffer read
pointer.
stringstream::str() returns a copy of the whole buffer, no matter where
the read pointer points to.

To clear a stringstream do:

ss.str(""); // clear the buffer
ss.clear(); // reset stream flags
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top