How to check if the input number integer not float?

前端 未结 3 1603
情深已故
情深已故 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:09

    Building on Raindrop7's solution, here's the full code to do what you need:

    #include <cstdio>
    #include <iostream>
    #include <cmath>
    using namespace std;
    
    int main()
    {
        double m;
        cout << "Your input is: "<<endl;
        cin >> m;
        while (cin.fail() || (m-floor(m)))
        {
            cout << "Error. Nubmer of elements has to be integer. Try again: " << endl;
            cin.clear();
            cin.ignore(256, '\n');  
            cin >> m;
        }
        int n = (int)m;
        return 0;
    }
    

    Here's a sample output:

    Your input is: 
    2.7
    Error. Nubmer of elements has to be integer. Try again: 
    erer
    Error. Nubmer of elements has to be integer. Try again: 
    2
    
    0 讨论(0)
  • 2020-12-20 08:17

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

    #inclide <iostream>
    using namespace std;
    int n;
    cout << "Your input is: "<<endl;
    while (!(cin >> 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.)
    0 讨论(0)
  • 2020-12-20 08:23

    You can try to convert the input string to a int using a std::istringstream. If it succeeds then check for eof() (after ignoring blank spaces) to see if the whole input was consumed while converting to int. If the whole input was consumed then it was a valid int.

    Something a bit like this:

    int input_int()
    {
        int i;
    
       // get the input
        for(std::string line; std::getline(std::cin, line);)
        {
            // try to convert the input to an int
            // if at eof() all of the input was converted - must be an int
            if((std::istringstream(line) >> i >> std::ws).eof())
                break;
    
            // try again
            std::cout << "Not an integer please try again: " << std::flush;
        }
    
        return i;
    }
    
    int main()
    {
        std::cout << "Enter an integer: " << std::flush;
    
        std::cout << "i: " << input_int() << '\n';
    }
    
    0 讨论(0)
提交回复
热议问题