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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...