1

According to my textbook, "C++ Primer Plus, Sixth Edition", if I input a character into an int variable, it is wrong behavior. So the variable doesn't change and the wrong input is stored in the buffer. Also, the cin object sets an error flag, and the cin method return false.

But, when I write code like the following and input a character into an int variable n, it becomes 0.

As I learned, it must be the first value which is 9.

Why does it become 0?

#include<iostream>
using namespace std;

int main()
{
    int n=9;
    cout << "now the number n  is = " << n << endl;
    cout << "enter the new number : ";
    cin >> n;
    cout << "new number n is = " << n << endl;
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
CD S
  • 43
  • 6
  • "*Why does it become 0?*" - because C++11 changed the behavior of `operator>>` to set the variable to 0 on failure. Prior to C++11, the variable was left unchanged. – Remy Lebeau Aug 04 '21 at 07:03
  • Ah!! It's because of the version of compiler??? – CD S Aug 04 '21 at 07:05
  • @CDS Not exactly. It's a different version of the language standard. One and the same compiler can compile a program for different versions of the language standard. But modern compilers will have C++14 or C++17 as default, whereas older versions of the compiler use an older language standard by default. – Lukas-T Aug 04 '21 at 07:21
  • I got it!! Thanks for your answer. – CD S Aug 04 '21 at 21:21

0 Answers0