How to restrict a user to a particular input in C++? | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 2

How to restrict a user to a particular input in C++?

What I mean is that for example you ask the user to input some data e.g his name(a string) and by accident or intentionaly if he enters data of irrelevent type, say if he enters some numbers(intigers) in place of string or vice versa. Then the program will crash down. So how to avoid this and keep the user engaged in the input until he enters the correct data? I am talking about C++ console based projects right now.

19th Feb 2018, 1:04 PM
Raja Kashif Ilyas
Raja Kashif Ilyas - avatar
3 Réponses
+ 8
You must use Exception handling.
19th Feb 2018, 1:15 PM
Muhd Khairul Amirin
Muhd Khairul Amirin - avatar
+ 3
usually this kind of problems occur if you want the user to inout a number and he enters a string instead. the system will crash trying to convert that string into a number. to avoid this kind of problem, make the inout variable a string and check if it contains only numbers before starting the program. if it doesnt, alert the user to inout only numeric values and end the program. you can also use a try catch to avoid the app crashing whenever a problem occurs
19th Feb 2018, 2:08 PM
Dominique Abou Samah
Dominique Abou Samah - avatar
+ 3
You will have to analyze the string and determine whether it really is of the type that you wanted or not. Then you can put these ifs inside a do...while loop and read till you receive a successful input. Eg : https://www.sololearn.com/discuss/1084865/?ref=app In this post, the code I posted reads input and stops only when true integers are received. You may change the if condition for strings. https://code.sololearn.com/cnxi7DID8NnK/?ref=app And in this code, I have declared some functions to determine the type of input. You may use these in the if...else blocks inside the loop.
19th Feb 2018, 3:50 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar