+ 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.
3 Answers
+ 8
You must use Exception handling.
+ 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
+ 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.