cin读取错误的类型时会覆盖我的初始化值吗? [英] cin overwriting my initialized value when it reads wrong type?

查看:142
本文介绍了cin读取错误的类型时会覆盖我的初始化值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,这是一个非常基本的问题,非常琐碎,但我只是在遵循编程原则和C ++的实践以及我读取字符串和int程序的行为与Bjarne Stroustrup所写的书不同,因此,如果他犯了一个错误,我会感到惊讶.无论如何,这是代码:

So this is a really basic question and super trivial but Im just going through programming principles & practices in c++ and my program for reading in a string and a int is behaving differently than the book which is written by Bjarne Stroustrup so id be surprised if he made a mistake. Anyway here's the code:

#include "..\std_lib_facilities.h"

int main()
{
    cout << "Please enter your first name and age\n";
    string first_name = "???"; // string variable
                               // ("???" means "don’t know the name")
    int age = -1;              // integer variable (1 means "don’t know the age")
    cin >> first_name >> age;  // read a string followed by an integer
    cout << "Hello, " << first_name << " (age " << age << ")\n";
}

当我在提示符下在终端中输入"22 Carlos"时,它输出"Hello,22(年龄0)",基本上使我的初始化值对错误检查毫无用处.这是C ++的新功能还是其他什么,这就是为什么书不对吗?

When I input "22 Carlos" into the terminal at prompt it outputs "Hello, 22 (age 0)" basically making my initialization value for error checking useless. Is this a new feature of c++ or something and thats why the book is wrong?

顺便说一句,即时通讯在Windows 7和-std = c ++ 11触发器上将GCC用于cygwin.

BTW im using GCC for cygwin on windows 7 and the -std=c++11 trigger.

推荐答案

这是 std :: basic_istream :: operator >> 自C ++ 11起:

This is a new feature of std::basic_istream::operator>> since C++11:

如果提取失败(例如,如果在期望数字的位置输入了字母),则值将保持不变,并设置故障位. (直到C ++ 11)

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)

如果提取失败,则将零写入值,并设置故障位. (自C ++ 11起)

If extraction fails, zero is written to value and failbit is set. (since C++11)

您应该改为检查流的状态,例如

You should check the status of stream instead, e.g.

if (cin >> age) {
    ... fine ....
} else {
    ... fails ...
}

这篇关于cin读取错误的类型时会覆盖我的初始化值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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