Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c++ - How to check if the input number integer not float?

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 to use like integer without fractional part.

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

So, how to make this code see if the input is float?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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(!line.empty() && (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() << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...