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
}
#include <iostream>
#include <conio.h>
#include <cstdlib>
usingnamespace 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;
}
elseif( bar == 13 ) // if presed enter
{
break; // leave the loop
}
elseif( !(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;
}