0

The following is my code:

#include <iostream>
using namespace std;

int main() {
  int num;
  cout<<"Enter a number: ";
  cin>>num;
  cout<<"The number is: "<<num;

  return 0;
}

If I enter a character or a string instead of an integer on the prompt for cin>>num, the value of num is returned as 0 everytime. Is it because it has been implemented that way in C++ or am I missing some trivial concept? Any answer would be of great help.

3
  • @AsteroidsWithWings Really? Commented Nov 10, 2020 at 16:53
  • @AsteroidsWithWings haha I mean what does he awaits to see after. my bet is char scan code Commented Nov 10, 2020 at 17:00
  • so it were double entendre thing. did you catch it? Commented Nov 10, 2020 at 17:18

2 Answers 2

4

This is a feature introduced in C++11. From cppreference;

before:

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)

now:

If extraction fails, zero is written to value and failbit is set. If extraction results in the value too large or too small to fit in value, std::numeric_limits::max() or std::numeric_limits::min() is written and failbit flag is set. (since c++11)

Note that before C++11 your code potentially invokes undefined behavior. If input fails you are using num uninitialized. In that case, 0 as output was just as valid as any other output (because undefined behavior is undefined).

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I do need to learn my way around cppreference :)
@Anjishnu some areas of the standard library are notorisouly difficicult for beginners (at least it was for me). When you read std::basic_istream<CharT,Traits>::somehting then for now you can read that as std::istream::something, it looks a bit more complicated than it actually is
0

Istreams objects have flags to detect bad input: whenever bad input is passed to cin there'll be a bad input flag set. By calling cin.fail() and checking if it evaluates to true you can actively monitor if input wasn't correct. In that case, cin will assign value 0 to the variable you passed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.