c++ - cin 在读取错误类型时会覆盖我的初始化值吗?

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

<分区>

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

#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 和 -std=c++11 触发器上使用 GCC for cygwin。

最佳答案

这是 std::basic_istream::operator>> 的新功能从 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)

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

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

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

关于c++ - cin 在读取错误类型时会覆盖我的初始化值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43795214/

相关文章:

c++11 - 创建共享库时,不能使用针对 `.rodata'的R_X86_64_32重定位;用-fPIC重新编译

c++ - 相同类型布局的变量结构是否与包含该类型数组的结构兼容?

c++ - 试图了解C++ 14(N4140)中的[basic.def.odr]/2

c++ - 如何围绕我的对象旋转相机?

c++ - 如何在 Windows 中从 C++ 程序执行另一个 exe

c++ - std::vector 与 std::array 性能对比

c# - 可以使用指针修改只读字段吗?但为什么?

c++ - 有效地写入文件

c++ - 原始树的子树

c++ - 如何将 blockng waitUntil() 方法写入使用 std::atomics 的池