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