0

I'm writing a program that gets a number from the user and print it, I want to check if the user's input is a number or not.

#include <iostream>

int main(){

    int x;

    std::cout << "Enter a number: ";
    std:;cin >> x;

    /*
    Here's what I want to do
    if (isInteger(x)){

        std::cout << "\nYour number is " << x << ;

    } else if (isNotInteger()){
        std::cout << "\nInvalid value\n\n";
    }
    */

    return(0);
}
  • Since you are streaming into an `int`, `std::cin` *will already check this for you*. (If the input is not an integer, the operation will fail - you can use `if (std::cin >> x)` or `if (std::cin.fail())` to check this.) – 0x5453 Feb 09 '21 at 21:19

1 Answers1

0

The stream's error state is set to failbit if operator>> fails to read a value. You can test for that condition, eg:

if (std::cin >> x) {
    std::cout << "\nYour number is " << x << ;
} else {
    std::cout << "\nInvalid value\n\n";
}

If you want to continue reading about a failure, you have to first call the stream's clear() method to reset the error state, and also read/remove the invalid data from the buffer, such as with the stream's ignore() method, eg:

if (std::cin >> x) {
    std::cout << "\nYour number is " << x << ;
} else {
    std::cout << "\nInvalid value\n\n";
    std::cin.clear();
    std::cin.ignore(std::numeric_liimits<std::streamsize>::max(), '\n');
}
Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620