I\'m very new to this C++ world and trying write a input validation function for numeric password. This is what I got so far:
#include
#incl
If there is a failure to convert then the stream itself evaluates to false so you can do this:
int get_int() {
int i;
std::cout << "Please enter a number: " << std::endl;
while(!(std::cin >> i)) {
std::cin.clear(); //clear flags
//discard bad input
std::cin.ignore(std::numeric_limits<std::streamsize>::max());
std::cout << "Incorrect, must be numeric: " << std::endl;
}
return i;
}
This looks like line oriented input. In which case, the usual solution
is to use getline
:
bool parseNumber( std::string const& text, int& results )
{
std::istringstream parser( text );
return parser >> results >> std::ws && parser.peek() == EOF;
}
int getNumber()
{
int results;
std::string line;
while ( ! std::getline( std::cin, line ) || ! parseNumber( line, results ) )
{
std::cin.clear();
std::cout << "Only 'numeric' value(s) allowed:";
}
return results;
}