我正在将字符串流中的数据提取到 string
和 double
中:
std::string word;
double num;
std::istringstream stream("hello x");
stream >> word >> num;
std::cout << word;
std::cout << num;
是否可以判断第二个标记 "x"
是否已成功解析为 int
?
在这种情况下,显然不会,x 的值为0
。
最佳答案
提取运算符(>>)将返回真或假,判断提取是否成功。
if (stream >> num)
cout << "success\n";
else
cout << "failed\n";
此外,您可能会看到在 istringstream
对象上设置了 failbit
if (stream.fail())
cout << "failbit is set\n";
关于c++ - 如何判断对变量的流提取是否失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26621675/