How to check if the input number integer not float?

前端 未结 3 1604
情深已故
情深已故 2020-12-20 07:42

I want to check if the input is valid, but when i do run this code I see that it checks only input for charcters. If i input a float number it will take it and going t

3条回答
  •  無奈伤痛
    2020-12-20 08:17

    The code below should be able to do what you are hoping to achieve:

    #inclide 
    using namespace std;
    int n;
    cout << "Your input is: "<> n) || cin.get() != '\n') {
        cout << "Error. Number of elements must be integer. Try again: " << endl;
        cin.clear();
        cin.ignore(256, '\n');  
    }
    

    The program asks the user to re-enter an integer if either of the following happens:

    1. If the program is unable to extract an integer from the std::cin stream. (For example, when a character or string is entered by the user)
    2. If, after an integer is extracted successfully, the next character in std::cin is not the new line '\n' character. (For example, when a number with a decimal point like 1.1 is entered, or when an integer followed by a character like 1a is entered.)

提交回复
热议问题