Hello everyone. I am trying to validate the user input but since I'm using unsigned long long, I'm unable to check against negative numbers. I only want the application to give give results if the input is positive. I also need a workaround for alphanumeric input.
From what I have so far, my program can differentiate between alphanumericals and numerical if the input starts with a character, an alphabet. But if I start with a number, it starts computing.
#include <iostream>
// return true if the next non-white-space character to be read from the input buffer is '-'
bool negative_input() { return ( std::cin >> std::ws ).peek() == '-' ; }
unsignedlonglong get_positive_integer_greater_than( unsignedlonglong lbound )
{
std::cout << "please enter an integer greater than " << lbound << ": " ;
unsignedlonglong number ;
if( negative_input() ) std::cout << "please enter a non-negative value. " ;
elseif( std::cin >> number ) // if the user entered a number
{
// return it if it is within the valid range
if( number > lbound ) return number ;
// not a valid choice; inform the user about the error
else std::cout << "value is not greater than " << lbound << ". " ;
}
else // the user entered a non-numberic value eg. abcd
std::cout << "invalid input. please enter a number. " ;
// we have not returned from the function, ergo input failure
std::cin.clear() ; // clear the (possible) failed state of the stream
std::cin.ignore( 1000, '\n' ) ; // throw the bad input away
std::cout << "try again\n" ;
return get_positive_integer_greater_than(lbound) ; // try again
}
int main()
{
constunsignedlonglong n = get_positive_integer_greater_than(99) ;
std::cout << "\nyou entered " << n << '\n' ;
}
@JLBorges - Thank you! Although, it would be better to have predefined function in say the standard library to ignore certain inputs like characters which don't belong to a data type. It would also be better to have new data types without any corresponding belonging to another data type. I wonder if they used separate binary values for each individual character when designing programming languages or not.