Skip to main content
GameDev.net gamedev.net
🔒 Locked

Getting a funny error with String Stream.

Started by utilae Jul 29, 2006 at 9:57 PM 2 replies 450+ views
Original Post
utilae
utilae
I am using C++. I'm trying to convert a string to an int, but I have this problem. The first string converts to an int, but the second one doesn't. It doesn't get set at all and becomes whatever funny number is in memory.

int nNumberOne,nNumberTwo;

g_StrStream.str("5");
g_StrStream>>nNumberOne;//convert string to int

g_StrStream.str("2");
g_StrStream>>nNumberTwo;//convert string to int

g_Log<<"nNumberOne="<<nNumberOne<<" nNumberTwo="<<nNumberTwo<<endl;
//nNumberOne=5  ,  nNumberTwo=56465466 (some funny number)

Anyone able to help?
HTML5, iOS and Android Game Development using Corona SDK and moai SDK
jflanglois
jflanglois
It's because you've reached EOF (End-Of-File). You need to clear() the stream before you can continue:
int nNumberOne,nNumberTwo;g_StrStream.str("5");g_StrStream>>nNumberOne;//convert string to intg_StrStream.clear();g_StrStream.str("2");g_StrStream>>nNumberTwo;//convert string to intg_Log<<"nNumberOne="<<nNumberOne<<" nNumberTwo="<<nNumberTwo<<endl;
scottdewald
scottdewald
You need reset state of the stream when you set it to a new string. Even though you reset the string value, if you don't clear the state, then it assumes its at the end of the buffer still.

int nNumberOne,nNumberTwo;g_StrStream.str("5");g_StrStream>>nNumberOne;//convert string to intg_StrStream.clear();  // NEWg_StrStream.str("2");g_StrStream>>nNumberTwo;//convert string to intg_Log<<"nNumberOne="<<nNumberOne<<" nNumberTwo="<<nNumberTwo<<endl;
SiCrane
SiCrane
At this point I would like to take a moment to say "I told you so":
Quote:
Original post by SiCrane
First, I highly recommend not using a global stringstream object. Also consider using boost::lexical_cast for this kind of thing.
//snip//
If you use a global stringstream object keep in mind that you may need to clear the eof bit after an extraction.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.