如何判断对变量的流提取是否失败

How can you tell if a stream extraction to a variable failed?

本文关键字:提取 是否 失败 变量 何判断 判断      更新时间:2023-10-16

我正在将字符串流中的数据提取到stringdouble:中

std::string word;
double num;
std::istringstream stream("hello x");
stream >> word >> num;
std::cout << word;
std::cout << num;

是否可以判断第二个令牌"x"是否成功解析为int

在这种情况下,它显然不会,并且x的值是0

提取运算符(>>)将返回true或false以判断提取是否成功。

if (stream >> num)
  cout << "successn";
else
  cout << "failedn";

此外,您可能会在istringstream对象上看到故障位设置

if (stream.fail())
  cout << "failbit is setn";