How to check if the input number integer not float?

前端 未结 3 1612
情深已故
情深已故 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 08:09

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

    #include 
    #include 
    #include 
    using namespace std;
    
    int main()
    {
        double m;
        cout << "Your input is: "<> 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
    

提交回复
热议问题