简体   繁体   中英

Unable to exit while loop (as data validation) while testing for string input in homework problem in C++

I'm trying to write a simple program where I see if a user qualifies for a loan.

I'm trying to do validation to make sure the user doesn't enter gibberish, and when I do, it doesn't exit the while loop even when it's not true anymore.

The while loop doesn't work.

#include <iostream>
using namespace std;

int main() {
  string employed;

  cout << "Are you currently employed?\n";
  cin >> employed;

  while (employed != "yeah" || employed != "no" || employed != "yes" ||
         employed != "Yes") {
    cout << "Enter yes or no.";
    cin >> employed;
  }
  // ...
}

Of course you wouldn't be able to pass the while loop, all string would satisfy the while condition. I think you meant:

while (employed != "yeah" && employed != "no" && employed != "yes" && employed != "Yes")

That is, employed is none of the controlled inputs.

Just change || to && in your while conditions.

while (employed != "yeah" && employed != "no" && employed != "yes" && employed != "Yes")
{
    cout << "Enter yes or no.";
    cin >> employed;
}

I'll try to explain what the problem is in more detail, let's simplify the while condition for a second:

while (employed != "yes" || employed != "no")

This means the loop will run as long as the inner expression evaluates to true. Suppose the user enters "yes" . Here's how that will play out in steps, replacing employed with its value "yes"

1) while ("yes" != "yes" || "yes" != "no")

we can see that "yes" != "yes" is false , so let's fill that in

2) while (false || "yes" != "no")

now we evaluate the right side of the or || operator. "yes" != "no" well, yes is not equal to no, so that is true

3) while (false || true)

Since it's a logical or operator, the result will be true as long if at least one of its operands is true. We have one true and one false, so the || operator produces true as a result

4) while (true)

Thus your loop never exits, because at least one of the right or left will always be true. Instead use the and operator && which is only true if both of its operators are true:

while (employed != "yes" && employed != "no")

Which we can read as "continue as long as employed is not "yes", and employed is not "no". You can chain on as many extra words as you would like to support.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM