By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,652 Members | 1,697 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,652 IT Pros & Developers. It's quick & easy.

std::stringstream::seekg

P: n/a
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
Aug 11 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
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

Aug 11 '05 #2

P: n/a
On 11 Aug 2005 04:00:55 -0700, sh*************@hotmail.com wrote:
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?
Aug 11 '05 #3

P: n/a
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

Aug 11 '05 #4

P: n/a
On 11 Aug 2005 04:15:30 -0700, sh*************@hotmail.com wrote:
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
Aug 11 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.