cin 在读取错误类型时会覆盖我的初始化值吗?
cin overwriting my initialized value when it reads wrong type?
所以这是一个非常基本的问题,而且非常琐碎,但我只是通过 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。
这是自 C++11 以来 std::basic_istream::operator>> 的新功能:
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 ...
}
试试这个:
cin >> first_name >> age; // read a string followed by an integer
//Check if cin failed.
if (cin.fail())
{
//Handle the failure
}
至于为什么它在失败时将整数设置为0,请看这里:
所以这是一个非常基本的问题,而且非常琐碎,但我只是通过 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。
这是自 C++11 以来 std::basic_istream::operator>> 的新功能:
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 ...
}
试试这个:
cin >> first_name >> age; // read a string followed by an integer
//Check if cin failed.
if (cin.fail())
{
//Handle the failure
}
至于为什么它在失败时将整数设置为0,请看这里: