Answer the question
In order to leave comments, you need to log in
Best option for checking input against multiple conditions in C++?
Actually, I want to know the most correct way to check input from cin for various conditions and display different messages for each. There are many verification options, but due to lack of experience I can not understand which one is more correct to use. So far I've settled on something like this:
do {
cin>>x;
if (x < 0) {
cout<<"x должно быть положительным числом"<<endl;
continue;
} else if (x == 0) {
cout<<"x не должно равняться нулю"<<endl;
continue;
} else if (x == 5) {
cout<<"x не должно равняться пяти"<<endl;
continue;
}
break;
} while (true);
Answer the question
In order to leave comments, you need to log in
You can simplify the code a bit:
while (true) {
cin>>x;
if (x < 0) {
cout<<"x должно быть положительным числом"<<endl;
} else if (x == 0) {
cout<<"x не должно равняться нулю"<<endl;
} else if (x == 5) {
cout<<"x не должно равняться пяти"<<endl;
} else {
break;
}
}
Decompile any variant and you will probably find out that this variant is already the best one.
The correct one that works can be removed for cleanliness.
(and remove else, prompted)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question