I'm a beginner in C++ and I'm currently practicing. I am trying to write a code that accepts only a five digit integer user input. For instance, the user inputs more than five digits, the program will ask the user again to input a number.
#include <iostream>
int main() {
int number = 0 ;
bool done = false ;
while( !done ) {
std::cout << "enter a five digit positive integer: " ;
if( std::cin >> number ) { // if the user entered an integer
if( number > 9'999 && number < 100'000 ) // if it is a five digit positive integer
done = true ; // we got a valid number as input; we can exit from the loop
else // number entered is out of range
std::cout << number << " is not a five digit positive integer. try again\n" ;
}
// you may want to ignore this part (non-integer input error handling) for now
// (ie. assume that the user will always enter some integer or the other)
else { // the user did not enter a number eg. the user entered 'abcd'
std::cout << "error: non-integer input. try again\n" ;
std::cin.clear() ; // clear the failed state of std::cin
std::cin.ignore( 1000, '\n' ) ; // and throw the bad input away
}
} // end while
std::cout << "the number you entered is " << number << '\n' ;
}