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"; } #包括“.\std\u lib\u facilities.h” int main() { cout

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"; } #包括“.\std\u lib\u facilities.h” int main() { cout,c++,c++11,language-lawyer,cin,C++,C++11,Language Lawyer,Cin,这是自C++11以来的一个新特性: 如果提取失败(例如,如果在预期数字的位置输入了字母),则该值将保持不变,并设置failbit。(直到C++11) 若提取失败,则将零写入值并设置failbit。(自C++11起) 您应该检查流的状态,例如 if (cin >> age) { ... fine .... } else { ... fails ... } 试试这个: cin >> first_name >> age; // read a st

这是自C++11以来的一个新特性:

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

若提取失败,则将零写入值并设置failbit。(自C++11起)

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

if (cin >> age) {
    ... fine ....
} else {
    ... fails ...
}
试试这个:

cin >> first_name >> age;  // read a string followed by an integer

//Check if cin failed.
if (cin.fail())
{
    //Handle the failure
}
至于为什么它在失败时将整数设置为0,请看这里:

我认为旧的(C++11之前的)行为对于一般类型(非内置类型)来说是不现实的。如果读取失败,则恢复旧值是无效的,我认为将读取对象保持在不一定是原始值的有效状态会使实现输入流代码的人的生活更轻松。