为什么输入 char 代替 int 总是显示值零?

Why does an input of char in place of int always display value zero?

以下是我的代码:

#include <iostream>
using namespace std;

int main() {
  int num;
  cout<<"Enter a number: ";
  cin>>num;
  cout<<"The number is: "<<num;

  return 0;
}

如果我在 cin>>num 的提示中输入字符或字符串而不是整数,则 num 的值每次都返回为 0。是因为它是在 C++ 中以这种方式实现的,还是我遗漏了一些微不足道的概念?任何答案都会有很大帮助。

这是 C++11 中引入的功能。来自 cppreference;

之前:

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set. (until C++11)

现在:

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. (since c++11)

请注意,在 C++11 之前,您的代码可能会调用未定义的行为。如果输入失败,您正在使用 num 未初始化。在那种情况下,0 作为输出与任何其他输出一样有效(因为未定义的行为是未定义的)。

Istreams 对象具有检测错误输入的标志:每当将错误输入传递给 cin 时,都会设置错误输入标志。通过调用 cin.fail() 并检查其计算结果是否为真,您可以主动监控输入是否不正确。在这种情况下,cin 会将值 0 分配给您传递的变量。