samedi 23 décembre 2017

Why does if(!(cin >> int)) accept a decimal number in the first iteration but not the other ones?

The following program is from a google tutorial and it's pretty straightforward, except when I input a decimal number.

#include <iostream>
using namespace std;

int main() {
  int input_var = 0;
  do {
    cout << "Enter a number (-1 = quit): ";

    if (!(cin >> input_var)) {
      cout << "You entered a non-numeric. Exiting..." << endl;
      break;
    }

    if (input_var != -1) {
      cout << "You entered " << input_var << endl;
    }

  } while (input_var != -1);

  cout << "All done." << endl;
  return 0;
}

if the input is an int (not -1) it outputs:

Enter a number (-1 = quit): 5
You entered 5
Enter a number (-1 = quit):

if it is a non-numeric:

Enter a number (-1 = quit): p
You entered a non-numeric. Exiting...
All done.

and that's exactly how it is supposed to work, but if it is a decimal number:

Enter a number (-1 = quit): 5.9
You entered 5
Enter a number (-1 = quit): You entered a non-numeric. Exiting...
All done.

I know how c++ behaves if you assign a double or a float to an int and in this case it outputs the truncated decimal number the first time and cin does not become false but the second iteration it does not even accept an input.

I would understand if it didn't accept it from the very beginning or if it just truncated the decimal and behaved the same as if it had had an int as input but why does it behave differently the first loop and differently the second loop?

Aucun commentaire:

Enregistrer un commentaire