Set a 4-digit int code with cin | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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! 😊

1st Dec 2017, 8:42 PM
Dimitris Petrakis
Dimitris Petrakis - avatar
4 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).
1st Dec 2017, 9:21 PM
Adam Schmitt
Adam Schmitt - avatar
+ 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.
1st Dec 2017, 10:44 PM
Dimitris Petrakis
Dimitris Petrakis - avatar
+ 1
And can I prevent the user from entering anything else instead of numbers when entering that string variable?
1st Dec 2017, 10:46 PM
Dimitris Petrakis
Dimitris Petrakis - avatar
+ 1
Yes, you check each character to make sure it is an integer instead of an alphabetic character using a for loop, for example.
1st Dec 2017, 10:49 PM
Adam Schmitt
Adam Schmitt - avatar