How to check if the input number integer not float?

前端 未结 3 1605
情深已故
情深已故 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: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';
    }
    

提交回复
热议问题