Limiting cin to n number of digits

Hi everyone. I would like to know if there is any way to limit to number of digits that can be entered using cin. I have successfully looped my code so that a number between 1 and 99 999 has to be entered otherwise an error message appears and the user is asked to enter another number.

My problem is that the variable I need to assign the value to must remain an int (school assignment restrictions), but if I enter any number that exceeds what an int can hold, the rest of my program outputs weirdly and I get stuck at the error message with no possibility to enter something else.

I would like to make it so if the user tries to enter a sixth digit (before actually pressing enter), it will only overwrite the fifth. Here's the code:

1
2
3
4
5
6
7
8
9
10
NbOri = 0;														
while(NbOri <1 || NbOri >=100000)
{
  gotoxy(0,0);
  cout <<"Nombre de pages originales: "; //"Number of original pages"
  clreol(); //Clears the rest of the line
  cin >>NbOri; // The int variable
  cout << endl << endl << setw((80 - LgNbInv) / 2) <<""; //Centering the error message
  cout << NbInv; //The error message
}
closed account (1v5E3TCk)
I hope that works, and ,f you dont understand any part of the code just ask me

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
35
36
37
38
39
40
41
42
43
44
#include <iostream>
#include <conio.h>
#include <cstdlib>

using namespace std;

int main()
{
    int foo=0;
    int bar;

    while( bar = _getch() )
    {


        if( bar == 8 ) // if presed backspace
            {
                foo /= 10; //divide by 10 to get rid of last digit
                system( "cls" );
                cout << foo;
                continue;
            }
        else if( bar == 13 ) // if presed enter
            {
                break; // leave the loop
            }

        else if( !(bar > 47 && bar < 58) ) // it provide it to enter a letter instead number
            continue;

          foo *= 10;
          foo +=  bar - '0'; //it converts char to int and adds it to foo
          system( "cls" );
          cout << foo;
    }



    cout << "\nFoo=" << foo << endl;

    return 0;

}


EDIT: Changed a commend
Last edited on
Thanks for replying. I'm not sure I get your code, especially how I'm supposed to add it to mine.
Topic archived. No new replies allowed.