I am completely new to C++ and am trying to write an extremely basic program, but I am having issues with initializing an integer. I have stripped it down to a very small program that still has the issue:
#include <iostream> using namespace std; int main() { cout << "Please enter your age\n"; int age = -1; cin >> age; cout <<"\n\n Your age is " << age << "\n\n"; }
I read that if I attempt to input a string, e.g. abc
to the age
variable, then the input should fail and the value should be left alone and therefore it should print Your age is -1
.
However, when I run this program and type abc
, then it prints Your age is 0
. Why?
The thing to do is to clear that flag and discard the bad input from the input buffer. See the C++ FAQ for this, and other examples, including adding a minimum and/or maximum into the condition.
cin. fail() - This function returns true when an input failure occurs. In this case it would be an input that is not an integer. If the cin fails then the input buffer is kept in an error state.
The "c" in C++ cin refers to "character" and "in" means "input". Thus, cin means "character input". The C++ cin object belongs to the istream class. It accepts input from a standard input device, such as a keyboard, and is linked to stdin, the regular C input source.
Every time you read from cin to a variable, the old contents of that variable is overwritten.
The behavior you want to observe changed in 2011. Until then:
If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.
But since C++11:
If extraction fails, zero is written to value and failbit is set. [...]
(From cppr.)
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