我有代码
#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
}
为什么变量
b
是0? stringstream 中是否有处理无效类型的规则(例如,值是“ab”但类型是 int)?
std::basic_ios::operator bool
来测试流是否处于失败状态。这是一个例子:
#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";
}
}