【问题标题】:How do I exit from do-while loop when a program was successfully terminated by user当程序被用户成功终止时,如何退出 do-while 循环
【发布时间】:2020-05-25 05:06:21
【问题描述】:

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

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

我的程序会检查要求并确定密码是否可以使用。

我现在遇到的障碍是我试图让程序运行到:

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

为了运行这样一个重复的过程,我决定使用 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;
}

【问题讨论】:

  • 替换 ||通过正确的 && 它会起作用的!

标签: c do-while continuous password-checker


【解决方案1】:

您不能将字符串与passwordInput != "quit" 进行比较,您必须使用strcmp() 并包括&lt;string.h&gt;。还要更改passwordClearance 上似乎不正确的测试:

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

【讨论】:

    【解决方案2】:

    为了让程序确定是时候爆发了,我有 使用以下命令:

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

    很遗憾,即使密码正确,我的程序仍然可以运行。

    这样做有两个问题:

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

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

      李>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多