#include <iostream>
#include <sstream>
using namespace std;
int get_4()
{
char c = '4';
stringstream s(ios::in);
s << c;
int i;
s >> i;
return i;
}
int main()
{
cout << get_4() << endl;
}
The conversion is not working for me. If I write a character ‘4’ or character array {‘4′,’\0’} to stringstream and then read it out to int i, I don’t get back the 4. What is wrong with the above code?
Because you set the
stringstreamto input-only — no output.If you check the
fail()bit after trying to extract theint, you’ll see it didn’t work:In your code, change:
to: