【问题标题】:cin overwriting my initialized value when it reads wrong type? [duplicate]cin 在读取错误类型时覆盖我的初始化值? [复制]
【发布时间】:2017-05-05 01:44:34
【问题描述】:

所以这是一个非常基本的问题,而且非常琐碎,但我只是通过 c++ 中的编程原理和实践,我的用于读取字符串和 int 的程序的行为与 Bjarne Stroustrup 所写的书不同,所以 ID 是如果他犯了一个错误,他会感到惊讶。无论如何,这是代码:

#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 (age 0)”,这基本上使我用于错误检查的初始化值毫无用处。这是c++的新特性还是什么,这就是这本书错的原因?

Edit1:顺便说一句,我在 Windows 7 上使用 GCC for cygwin 和 -std=c++11 触发器。

【问题讨论】:

  • 我认为旧的(C++11 之前的)行为对于一般类型(非内置类型)是不现实的。如果读取失败,恢复旧值效率不高,我认为让读取对象处于不一定是原始值的有效状态会使实现输入流代码的人更轻松。

标签: c++ c++11 language-lawyer cin


【解决方案1】:

这是std::basic_istream::operator>>自C++11以来的一个新特性:

如果提取失败(例如,如果在需要数字的地方输入了字母),则值保持不变并设置失败位。 (直到 C++11)

如果提取失败,则将零写入 value 并设置 failbit。 (C++11 起)

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

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

【讨论】:

    【解决方案2】:

    试试这个:

    cin >> first_name >> age;  // read a string followed by an integer
    
    //Check if cin failed.
    if (cin.fail())
    {
        //Handle the failure
    }
    

    至于为什么在失败时将整数设置为0,请看这里:

    Why does cin, expecting an int, change the corresponding int variable to zero in case of invalid input?

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 2016-09-20
      • 2020-03-18
      • 2015-01-13
      • 2011-09-25
      • 1970-01-01
      相关资源
      最近更新 更多