stringstream used to convert int to string does work only once?

F

Field

Hi,

the following snippet shows once executed this output:
2
2

I'd have rather expected this output:
2
10

Does anyone know why?

thx4hints,

FF

#include <iostream>
#include <sstream>
using namespace std;

int main(void)
{
string apName;
stringstream ss;

ss << 2;
ss >> apName;
cout << apName << endl;
ss << "10";
ss >> apName;
cout << apName << endl;
return 0;
}
 
V

Victor Bazarov

Field said:
the following snippet shows once executed this output:
2
2

I'd have rather expected this output:
2
10

Does anyone know why?

Sure. See below.
thx4hints,

FF

#include <iostream>
#include <sstream>
using namespace std;

int main(void)
{
string apName;
stringstream ss;

ss << 2;
ss >> apName;
cout << apName << endl;
ss << "10";
ss >> apName;
cout << apName << endl;
return 0;
}

#include <iostream>
#include <sstream>
using namespace std;

int main(void)
{
string apName;
stringstream ss;

ss << 2;
ss >> apName;
cout << apName << endl;
ss << "10";
if (ss >> apName)
cout << apName << endl;
else
cout << "Could not convert\n";
return 0;
}


V
 
S

Steven T. Hatton

Field said:
Hi,

the following snippet shows once executed this output:
2
2

I'd have rather expected this output:
2
10

Does anyone know why?


I don't believe the problem is related to converting an int to a string. It
seems to be related to the state of stringstream after the first input and
output. I'm not sure exactly what state it's put into, but if the state is
reset, the second sequence of calls will work as expected. I'll play
around a bit more to see if I can't find a way to determine the exact state
the stringstream is in after the first sequence of calls.
 

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

Forum statistics

Threads
473,774
Messages
2,569,600
Members
45,180
Latest member
CryptoTax Software
Top