So it has come to my understanding that cin.fail() has some drawbacks, namely
if, say, 1ssssss is entered, the input will be accepted. So I am trying to find a work around but I am having trouble.
The simplest solution I can think of is if that program detects something that isn't an integer it will prompt the user to retry with only an int.
I want to make it so the user can only input numerical values.
void inputValidation(string &choice)
{
bool charRead = false;
cout << "charRead" << charRead << endl;
getline(cin, choice);
int index = 0;
for (int i = 0; i < choice.length(); i++)
{
if (isalpha(choice[i]))
{
charRead = true;
cout << "charRead" << charRead << endl;
}
}
while (charRead== true)
{
for (int i = 0; i < choice.length(); i++)
{
if (isalpha(choice[i]))
{
cout << "That was an invalid input. Please omit characters." << endl;
//cin.clear();
//cin.ignore(25);
getline(cin, choice);
}
else charRead = false;
}
}//end loop
}
The code will deny inputs like "2s" for awhile but will then go accept them eventually. I've tried cin.clear and cin.ignore but they don't seem to be helping :(
#include <iostream>
int get_int( constchar* prompt, int min_value, int max_value )
{
std::cout << prompt << " [" << min_value << ',' << max_value << "]: " ;
int number ;
// if the user entered an int and the next character in the input stream is a white space
if( std::cin >> number && std::isspace( std::cin.peek() ) )
{
// in the entered number is within valid range, return it
if( number >= min_value && number <= max_value ) return number ;
else std::cout << "input error: the value is out of range." ;
}
else std::cout << "input error: not an integer." ;
// if we reached here, there was an input error. clean up and try again
std::cin.clear() ;
std::cin.ignore( 1000, '\n' ) ;
std::cout << " try again.\n" ;
return get_int( prompt, min_value, max_value ) ;
}
int main()
{
constint n = get_int( "enter a number", 10, 99 ) ;
std::cout << n << '\n' ;
}
To perform a string-to-numeric type cast. Catch the Invalid_Argument exception if it is thrown (when a string can't be converted to numeric) and break out of the while loop when the exception isn't thrown?
The user will ALWAYS press ENTER at the end of EVERY input.
Hence, get input as a string, then parse. If all you want is a number, and nothing else, it becomes as easy as ElusiveTau said: attempt a string→whatever conversion.
I have a function that I use regularly, called “string_to”: