0
How i can stop the program to input an invalid code. i am asking for a number then the user enter a letter how i can prevent it?
int accnum,bl; cout<<"Enter Account Number : "; cin>>accnum //now how to stop it pls help me because idk how to stop it while(accnum < 0 || accnum > 9) { cout<<"Invalid Account Number. It must be 0 to end"; //what if the user enter letter? cout<<"Enter Account Number"; cin>>accnum; } //then i dont want it to display the another cout. how i can stop displaying the cout cout<<"Enter Balance"; cin >>bl
1 Antwort
0
One thing you could do is to get the ascii equivalent of the input. Store the input as character type then typecast it to int.
char accnum;
cin >> accnum;
int ascii = (int)accnum; //ascii will have value of 48 if accnum = 0, 49 if accnum = 1, ... 57 if accnum = 9.
This would work because each character has an equivalent decimal in ascii.
Then you could just do:
if ( ascii < 48 || ascii > 57 ){
cout << "Enter a number" << endl;
}
else{
int input = ascii - 48; //this will return the original number
}
let me know if this has been helpful