You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

密码验证循环程序问题咨询:多次输入验证逻辑错误排查

问题排查与修复

你的代码核心问题出在错误输入后的处理逻辑:当输入密码错误时,你直接将password设为NULL,导致循环条件password != NULL不成立,循环直接终止,程序跳转到"Login failed!"的输出,完全没机会接收下一次输入尝试。

修复方案

把错误分支里的password = NULL;替换成重新打印输入提示并调用fgets读取新输入的逻辑,让循环能持续接收用户输入,直到密码正确或stdin被关闭。

修正后的代码

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

#define MAX_BUFFER_SIZE 80

/* Prompts user for password, waits for correct password */
void wait_for_correct_password(void) {
    char buffer[MAX_BUFFER_SIZE];

    char* password = NULL;
    // 第一次输入提示
    printf("Enter password: ");
    password = fgets(buffer, MAX_BUFFER_SIZE, stdin);
    
    while (password != NULL) {
        if (strcmp(password, "password1\n") == 0) {
            printf("Password correct!\n");
            break;
        } else {
            // 错误输入后重新提示并读取新输入
            printf("Enter password: ");
            password = fgets(buffer, MAX_BUFFER_SIZE, stdin);
        }
    }

    if (password == NULL) {
        printf("\nLogin failed!\n");
    }

}

int main(int argc, char** argv){
    wait_for_correct_password();
}

关键修改说明

  • 移除了错误分支里的password = NULL;,改为重新触发输入流程,保证循环能持续执行
  • 保留了每次输入前的提示文本,让用户明确知道需要继续尝试输入

内容的提问来源于stack exchange,提问作者HY2000

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 06:06:34