为什么在输入为int的情况下cin期望为int时将相应的int变量更改为零? [英] Why does cin, expecting an int, change the corresponding int variable to zero in case of invalid input?

查看:77
本文介绍了为什么在输入为int的情况下cin期望为int时将相应的int变量更改为零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对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:


如果提取失败(例如,如果在预期数字的位置输入了字母),则值将保持不变,并设置故障位。

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

但是从C ++ 11开始:

But since C++11:


如果提取失败,则将值写入零,并且故障位已设置。 [...]

If extraction fails, zero is written to value and failbit is set. [...]

(来自 cppr 。)

这篇关于为什么在输入为int的情况下cin期望为int时将相应的int变量更改为零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆