Question Details

No question body available.

Tags

c++ initialization cin

Answers (2)

Accepted Answer Available
Accepted Answer
May 15, 2026 Score: 10 Rep: 126,127 Quality: High Completeness: 60%

You get 0 because your compiler has implemented the resolution of LWG696.

According to the C++98 standard, the value should be left unchanged on extraction failure. That was considered to be a defect and the correct behavior should be to set it to zero in your case. Since it was considered being a defect, modern compilers will therefore set it to zero even in C++98 mode.

May 15, 2026 Score: -5 Rep: 2,037 Quality: Low Completeness: 60%

Some C++ streams do not leave the old value untouched.
For example:
Let's say you have this as your input:
32 David

When this line executes:

cin >> firstname >> age;

first
name is a string, so it reads "32".

Then age is an int, so the stream tries to read "David" as an integer. That fails.

When formatted extraction into an integer fails, the stream sets fail-bit, and the target integer is set to 0. So your age becomes 0, not -1.

You can try adding these lines, so after reading input, this checks whether the read succeeded

cin >> first_name >> age;

if (!cin) { cout age) { cout