问题描述
我对C ++完全陌生,正在尝试编写一个非常基本的程序,但是在初始化整数时遇到问题。我将其简化为一个仍然有问题的小型程序:
I am completely new to C++ and am trying to write an extremely basic program, but I am having issues with initializing an integer. I have stripped it down to a very small program that still has the issue:
#include <iostream>
using namespace std;
int main()
{
cout << "Please enter your age\n";
int age = -1;
cin >> age;
cout <<"\n\n Your age is " << age << "\n\n";
}
我读到如果我尝试输入字符串,例如 abc
到 age
变量,则输入应该失败并且该值应保留为空,因此应打印您的年龄是-1
。
I read that if I attempt to input a string, e.g. abc
to the age
variable, then the input should fail and the value should be left alone and therefore it should print Your age is -1
.
但是,当我运行此程序并键入 abc
,然后显示您的年龄是0
。为什么?
However, when I run this program and type abc
, then it prints Your age is 0
. Why?
推荐答案
您要观察的行为在2011年发生了变化。
The behavior you want to observe changed in 2011. Until then:
但是从C ++ 11开始:
But since C++11:
(来自。)
这篇关于为什么在输入为int的情况下cin期望为int时将相应的int变量更改为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!