C++ 不提供任何关于在输入失败时保持变量完整的保证吗?对于旧版本的 gcc,像这样的程序会在失败时保留 i 的 -1 值(例如,如果输入的是字母而不是输入的数字)。在 Ubuntu 10.10 (gcc 4.4.5) 中,如果输入失败,i 将重置为零。
#include <iostream>
int main()
{
int i = -1;
std::cin >> i;
std::cout << "i = " << i << '\n';
return 0;
}
这种行为破坏了我的很多代码。我想 gcc 的人知道他们在做什么,这很可能是我的错误。如果有人知道该标准,我想知道它对这种情况的看法。
谢谢。
最佳答案
不要依赖变量。依赖流的状态:
if (std::cin >> i) // "if (!std::cin.fail())" would also work
{
// ok
}
else
{
// error
}
至于为什么行为发生了变化,那是因为C++标准已经进化了:
来自 C++03:
If an error occurs, val is unchanged; otherwise it is set to the resulting value.
来自 C++0x(好吧..来 self 有权访问的最后一个草稿):
The numeric value to be stored can be one of:
- zero, if the conversion function fails to convert the entire field.
- the most positive (or negative) representable value, if the field to be converted to a signed integer type represents a value too large positive (or negative) to be represented in val.
- the most positive representable value, if the field to be converted to an unsigned integer type represents a value that cannot be represented in val.
- the converted value, otherwise.
关于c++ - C++ 是否应该在输入失败时保持变量完好无损?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3968972/