当用户成功终止程序时,如何退出 do-while 循环

How do I exit from do-while loop when a program was successfully terminated by user

我一直在开发一个检查密码是否合格的程序。

为了使密码符合条件,它至少需要:一个大写字母;一个号码;和一个美元符号。

我的程序会检查要求并确定密码是否合适。

我现在遇到的障碍是我尝试编写程序 运行 直到:

  1. 用户通过键入 "quit";
  2. 退出程序
  3. 或者如果用户键入正确形式的所需密码。

为了运行这样一个重复的过程我决定使用do-while循环。为了让程序确定是时候爆发了,我使用了以下命令:

do {...} while (passwordInput != "quit" || passwordClearance != 1);

不幸的是,即使密码正确,我的程序仍然运行

请给我一个线索,我该如何在一切顺利的时候从重复的过程中解脱出来。

// challenge: 
// build a program that checks when user enters a password for an uppercase letter, a number, and a dollar sign.
// if it does output that password is good to go.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char passwordInput[50];
    int digitCount = 0;
    int upperCharacterCount = 0;
    int dollarCount = 0;
    int passwordClearance = 0;

    do {
        printf("Enter you password:\n");
        scanf(" %s", passwordInput);

        for (int i = 0; i < strlen(passwordInput); i++) {
            if (isdigit(passwordInput[i])) {
                digitCount++;
                //continue;
            } else
            if (isupper(passwordInput[i])) {
                upperCharacterCount++;
                //continue;
            } else
            if (passwordInput[i] == '$') {
                dollarCount++;
                //continue;
            }
        }

        if ((dollarCount == 0) || (upperCharacterCount == 0) || (digitCount == 0)) {
            printf("Your entered password does not contain required parameters. Work on it!\n");
        } else {
            printf("Your entered password is good to go!\n");
            passwordClearance = 1;
        }
    } while (passwordInput != "quit" || passwordClearance != 1);

    return 0;
}

In order for program to determine that it is time to break out, I have used the following command:

do{...} while(passwordInput != "quit" || passwordClearance != 1);

Unfortunately my program still runs even if the password was correct.

这有两个问题:

  1. 逻辑错误。 while 表达式的计算结果为真,如果 组件关系表达式的计算结果为真,则导致循环循环。因此,要退出循环,两者都必须为假。您需要 && 而不是 ||,以便在其中一个表达式为假时退出循环。

  2. passwordInput != "quit" 将始终计算为真,因为您正在比较两个不同的指针。要将数组 passwordInputcontents"quit" 表示的数组的 contents 进行比较,您应该使用 strcmp()函数。

您不能将字符串与 passwordInput != "quit" 进行比较,您必须使用 strcmp() 并包含 <string.h>。同时更改 passwordClearance 上似乎不正确的测试:

do {
    ...
} while (strcmp(passwordInput, "quit") != 0 || passwordClearance != 0);