c++ - C++ 是否应该在输入失败时保持变量完好无损?

标签 c++ iostream

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/

相关文章:

c++ - 如何更新文件中特定行的数据?

java - 使用不同的 IO 流写入/读取文件的正确方法是什么

C++,STL。从 vector<string> 中删除具体值?

c++ - 折叠 TreeView 中的所有节点,最后展开的节点除外

c++ - 为什么 istream_iterator<unsigned char, unsigned char> 抛出 std::bad_cast?

c++ - 为什么 iostream::eof 在循环条件(即 `while (!stream.eof())` )内被认为是错误的?

c++ - MinGW : How to upgrade GCC/G++ to version 5 on Windows?

c++ - 如何使用 boost::regex 进行多次替换

c++ - 如何加快 C++ 中的矩阵乘法?

c++ - 如何指向输入流?