Hi,
Keyboard input validation is always a challenge. This function handles some usual cases:
#include <sstream>
template <class Num>
bool Validate(const std::string& input, Num& num)
{
Num tmp;
std::istringstream iss(input);
iss >> std::skipws >> tmp >> std::skipws;
return iss.eof() && !iss.fail() ? num = tmp, true : false;
}
Check with:
#include <iostream>
int main()
{
std::string input;
for (;;)
{
std::getline(std::cin, input); int i = 0;
bool bint = Validate(input, i);
float f = 0;
bool bfloat = Validate(input, f);
}
return 0;
}
"123", " 123 " "-123" are validated as int and float.
"12 3", " 12 3 " "- 123" are invalidated as int and float.
"123.", " .123 " "-12.3" " -.123e4 " are invalidated as int and validated as float.
cheers,
AR