std::stringstream::seekg

D

Dylan

Hi again,

In the following program I expected step 3 to assign the values 1 and
2 to iVal1 and iVal2 yet it appears ss.seekg(0, std::ios::beg) does
not move the read position back to the beginning of the stream as
expected.

//-----------------------------------------------------------------------------
#include <iostream>
#include <sstream>

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

//2. read the values 1 & 2 from the buffer and assign to iVal1 &
iVal2
int iVal1=-1, iVal2=-1;
ss >> iVal1 >> iVal2;
std::cout << "\n" << iVal1 << "," << iVal2;

//3. now move the read position back to the beginning of the stream
and read
//the values again
ss.seekg(0, std::ios::beg);
iVal1=-1; iVal2=-1;
ss >> iVal1 >> iVal2;
std::cout << "\n" << iVal1 << "," << iVal2;

//4. write the buffer to make sure it still contains "1 2" [OK]
cout << "\n" << ss.str();

return 0;
}

//-------------------------------------------------------------------------------

output from above is:

1,2
1,2
-1,-1
1,2


How can i move the read position back to the start of the buffer?

thanks
 
S

shanemjtownsend

You have

std::cout << ss.tellg();

this will print out the current read position, place it directly after
ss.seekg(0, std::ios::beg);

and it prints out 0
 
D

Dylan

You have

std::cout << ss.tellg();

this will print out the current read position, place it directly after
ss.seekg(0, std::ios::beg);

and it prints out 0


so why am I not getting the expected result?
 
S

shanemjtownsend

Actually no you haven't add this ss.clear(); before your ss.seekg(0,
std::ios::beg); statement
You have to clear the state of the stream [eofbit or failbit may have
been set] Probably the former since you already read from the stream
and you have to clear it before you can reset the read position.

ss.clear();
ss.seekg(0, std::ios::beg);

HTH
SMJT
 
D

Dylan

Actually no you haven't add this ss.clear(); before your ss.seekg(0,
std::ios::beg); statement
You have to clear the state of the stream [eofbit or failbit may have
been set] Probably the former since you already read from the stream
and you have to clear it before you can reset the read position.

ss.clear();
ss.seekg(0, std::ios::beg);

HTH
SMJT

That's it! Thanks very much
 

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

Similar Threads


Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top