Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does cin, expecting an int, change the corresponding int variable to zero in case of invalid input? [duplicate]

Tags:

c++

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?

like image 589
Thompson Avatar asked Sep 03 '15 14:09

Thompson


People also ask

How does c++ handle invalid input?

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.

What causes CIN failure?

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.

What does if Cin mean in c++?

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.

Does CIN overwrite?

Every time you read from cin to a variable, the old contents of that variable is overwritten.


1 Answers

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.)

like image 77
Baum mit Augen Avatar answered Oct 14 '22 16:10

Baum mit Augen