Input Validation with integers

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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' ;
}
You need to state your actual problem (and show some code).

A suggestion: input a string. Check that:
- it has length 5;
- all its characters are digits;
- it doesn't start with 0.

If all is OK then you can convert it with std::stoi()
Topic archived. No new replies allowed.