So this is a really basic question and super trivial but Im just going through programming principles & practices in c++ and my program for reading in a string and a int is behaving differently than the book which is written by Bjarne Stroustrup so id be surprised if he made 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 input "22 Carlos" into the terminal at prompt it outputs "Hello, 22 (age 0)" basically making my initialization value for error checking useless. Is this a new feature of c++ or something and thats why the book is wrong?
Edit1: BTW im using GCC for cygwin on windows 7 and the -std=c++11 trigger.
This is a new feature of std::basic_istream::operator>> since 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)
You should check the status of stream instead, e.g.
if (cin >> age) {
... fine ....
} else {
... fails ...
}
Try this:
cin >> first_name >> age; // read a string followed by an integer
//Check if cin failed.
if (cin.fail())
{
//Handle the failure
}
As to why it sets the integer to 0 upon failure, have a look here:
Why does cin, expecting an int, change the corresponding int variable to zero in case of invalid input?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With