并且表现得像 OR

AND behaving like OR?

本文关键字:OR      更新时间:2023-10-16

我正在评估一个输入并将其结果(由空格分隔)分配给两个变量。 不幸的是,如果用户=="用户"或密码=="通过",它似乎打破了循环!

    #include <iostream>
    #include <string>
    using namespace std;
    int main()
    {
        string username;
        string password;
        do {
            cout<<"Please enter the correct username and password.n";
            cin>>username>>password;
            cin.ignore();
        } while (username != "user" && password != "pass");
        cout<<"username and password correct";
    }

你真的需要一个OR:

while (username != "user" || password != "pass");

这不是一个C++问题,而是一个布尔逻辑问题。例如,参见德摩根定律。

要理解你的错误,是时候看看德摩根定律了:

"不是(A或B)

"与"(不是A)和(不是B)"相同

所以你的代码就像写:

!(username == "user" || password == "pass")
只要在

while 关键字之后指定的条件为 true,do..while 循环就会继续执行。您希望循环持续到username != "user"password != "pass" .

现在让我们假设,username == "user"password == "abc".然后,条件的第一部分将得到满足,但第二部分不会。所以你的循环将结束。

您真正想做的是继续循环,只要username != "user"password != "pass"。您可以通过以下方式编写它:

(...)
while (username != "user" || password != "pass");

或者,哪个更清楚一点:

while (!(username == "user" && pass == "pass"));
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string username;
    string password;
    label:
    cout<<"Please enter the correct username and password.n";
    cin>>username>>password;
    cin.ignore();
    if((username != "user") || (password != "pass"))
        goto label;
    cout<<"username and password correct";
}
相关文章:
  • 没有找到相关文章