+ 1
Set a 4-digit int code with cin
I get the user to enter a 4-digit code. How can I secure that he does indeed enter a strictly 4-digit code (int) and not a 3-digit code for instance? How can I set that int to be of a 4-digit length? Thanks a lot in advance! đ
7 Answers
+ 1
The best option is to take the input as a string and convert each character to an int to get the 4 digit code. This allows you to handle 4 digit code that start with 0 (for example 0123).
+ 1
Hi and thanks for your answers! yes, 0663 is a valid 4 digit code. So, I guess it will indeed have to be a string, right? but then again, how can I make sure that the user does not enter characters? like a4b7 for instance? I want to make sure that the user will enter a 4 digit number from 0000 to 9999.
+ 1
And can I prevent the user from entering anything else instead of numbers when entering that string variable?
+ 1
Yes, you check each character to make sure it is an integer instead of an alphabetic character using a for loop, for example.