Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 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 Reply

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() << '
';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...