-2

I am not sure if I understand cin.fail() correctly. I am trying to get it to return true when a user does not put in an integer.

#include <iostream>
using namespace std;

int main() {
    int number;

    cout << "Please enter a positive integer: ";
    cin >> number;
    cout << cin.fail();

    return 0;
}

Whenever I enter a non-integer (like 55.687) it returns 0(false) for the cin.fail(). I am not sure why. Any help would be greatly appreciated.

Reagan Cuthbertson
  • 330
  • 1
  • 2
  • 9
  • 5
    Try printing `number`. It will be `55`. The remaining text on `std::cin` will be `.687`. – Justin Sep 04 '18 at 23:32
  • It does print 55. I just don't understand how my code is any different than the first responder on [this](https://stackoverflow.com/questions/18728754/checking-input-value-is-an-integer) question. – Reagan Cuthbertson Sep 04 '18 at 23:39
  • @ReaganCuthbertson _"EDIT: To address the comment below regarding input like 10abc, one could modify the loop to accept a string as an input. Then check the string for any character not a number and handle that situation accordingly. "_ – πάντα ῥεῖ Sep 04 '18 at 23:42

1 Answers1

3

The stream has not yet failed.

When >> reads into an integer, it stops as soon as it finds a character that can't be in the integer. In the case of "55.687", that's the '.' character. So cin >> number reads 55 into number, and the ".687" remains in the stream for future reading.

Given the same input

int main() {
    int number;

    cout << "Please enter a positive integer: ";
    cin >> number;
    cin >> number;
    cout << cin.fail();

    return 0;
}

The second cin >> number would fail because '.' cannot be parsed into an int. Example: https://ideone.com/iB3aNk

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
user4581301
  • 33,082
  • 7
  • 33
  • 54