I have a code
#include <iostream>
#include <sstream>
using namespace std;
int main() {
stringstream ss("123 ab 4");
int a, b, c;
ss >> a;
ss >> b;
ss >> c;
cout << "XXX_ " << a << ' ' << b << ' ' << c << endl; // XXX_ 123 0 796488289
}
Why variable b
is 0? Is there a rule of handling invalid type in stringstream (e.g. value is "ab" but type is int)?
In order to test whether the conversion was successful, you should test whether the stream is in a failed state, for example by calling std::basic_ios::operator bool
(which is a function in a base class of std::stringstream
). Here is an example:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss( "123 ab 4" );
int a, b, c;
ss >> a;
ss >> b;
ss >> c;
if ( ss )
{
std::cout << "Conversion successful:\n";
std::cout << a << '\n' << b << '\n' << c << '\n';
}
else
{
std::cout << "Conversion failure!\n";
}
}
This program has the following output:
Conversion failure!
You can also test the stream state after every single conversion operation, for example like this:
#include <iostream>
#include <sstream>
int main()
{
std::stringstream ss( "123 456 ab 4" );
for (;;)
{
int i;
ss >> i;
if ( !ss )
break;
std::cout << "Successfully converted: " << i << '\n';
}
std::cout << "Unable to convert any more numbers.";
}
This program has the following output:
Successfully converted: 123
Successfully converted: 456
Unable to convert any more numbers.