1
    int value(0);
    while (!(std::cin >> value)) { //THIS LINE RIGHT HERE IS BUGGING ME(am really a noob)
        cout << "you entered a non-digit character\n";
        cin.clear();
        cin.ignore();
    }

this just stops people from entering letters instead of a number but i wanna know HOW it does it

4 Answers 4

2

Treating cin as a Boolean value tells you whether it's in a failure state. if ( cin ) is shorthand for if ( cin.ok() ). So the loop continues as long as the input stream is not OK, after taking some input.

Getting bad input is one way to get to a failure state. To get out of the state, call clear(), and to ignore the offending input, call ignore(). Then you can try again, as in this loop.

2
  • 1
    Doesn't ignore only ignore one character? Isn't there a better solution, like ignoring until a white-space or until '\n'?
    – dyp
    Commented Oct 2, 2013 at 23:33
  • @DyP Pass additional arguments to ignore more characters or up to a given character. Commented Oct 2, 2013 at 23:59
1

If what cin received's data type isn't compatible with value, then basically it returns as false.

0

cin >> value returns the cin object as a result. And it evaluates as false if the user-entered type doesn't match the specific overload (in your code, it's int), or cannot be implicitly converted to it.

0

cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin.

operator >> overload for streams returns a reference to the same stream and this can be evaluated in a boolean condition to true or false based on internal state of stream through a conversion operator. cin provides formatted stream extraction.

The operation

int value;
!(std::cin >> value)

will fail if numeric value is entered and will return true if non-numeric value is entered.

    cin.clear(); // will reset the state of stream
    cin.ignore(); // ignore one or more characters

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.