Consider the following code:
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
stringstream ss;
ss << string("12");
int h;
ss >> h;
cout << h << endl;
ss.str(string("")); // clear the content of ss
ss << string("30");
int m;
ss >> m;
cout << m << endl;
return 0;
}
Running the above code yields some random output:
12
0
At some other times, the following output is observed:
12
4
I expected the output to be simply:
12
30
Why did I get the unexpected results?
Also, what should be the best way to parse a string s
to int i
without necessary C++11 support? Should it be int i = atoi(s.c_str())
?