J
J
JustFailer2016-06-06 18:42:15
Programming
JustFailer, 2016-06-06 18:42:15

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

3 answer(s)
A
Anton Zhilin, 2016-06-06
@JustFailer

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;
  }
}

#
#algooptimize #bottize, 2016-06-06
@user004

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)

K
kozura, 2016-06-07
@kozura

Like this, minimal and without continue.

int x;
while (true) {
  cin >> x;
    
  if (x <= 0) {
    cout << "x должно быть положительным числом" << endl;
  } else if (x == 5) {
    cout << "x не должно равняться пяти" << endl;
  } else {
    break;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question