Cin overwrites my initialized value when it reads the wrong type?
So this is really a basic question and super trivial, but I'm just looking at C ++ programming principles and practices and my inline and int reader behaves differently than the book written by Bjarne Stroustup, so id wondered if he's 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";
}
When I type "22 Carlos" into the terminal when requested, it prints out "Hello, 22 (age 0)", basically rendering my error checking initialization value useless. Is this a new C ++ feature or something else, and why the book is wrong?
Edit1: BTW im using GCC for cygwin on Windows 7 and trigger -std = C ++ 11.
source to share
This is the new std :: basic_istream :: operator "> function , since C ++ 11:
If the extraction fails (for example, if a letter was entered in which a digit is expected), the value is left unchanged and the bitbit is set. (before C ++ 11)
If the extraction fails, zero is written to the value and failbit is set. (since C ++ 11)
Instead, you should check the status of the stream, eg.
if (cin >> age) {
... fine ....
} else {
... fails ...
}
source to share