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

密码验证函数满足要求却返回false的问题排查

密码检查程序逻辑错误分析与修复

你的判断逻辑完全错了——你在valid函数里要求同一个字符同时是大写字母、字母数字、标点符号,这根本不可能实现:一个字符要么是字母,要么是标点,不可能同时满足。这就是为什么符合要求的密码也被拒绝的原因。

正确的做法应该是:遍历整个密码字符串,分别检查是否存在至少一个大写字母、小写字母、数字和标点符号,用四个标记变量记录这些条件是否满足,最后判断四个条件是否全部达成。

修复后的代码如下:

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

bool valid(string password);

int main(void)
{
    string password = get_string("Enter your password: ");
    if (valid(password))
    {
        printf("Your password is valid!\n");
    }
    else
    {
        printf("Your password needs at least one uppercase letter, lowercase letter, number and symbol\n");
    }
}

bool valid(string password)
{
    bool has_upper = false;
    bool has_lower = false;
    bool has_digit = false;
    bool has_punct = false;

    for (int i = 0; i < strlen(password); i++)
    {
        if (isupper(password[i]))
        {
            has_upper = true;
        }
        else if (islower(password[i]))
        {
            has_lower = true;
        }
        else if (isdigit(password[i]))
        {
            has_digit = true;
        }
        else if (ispunct(password[i]))
        {
            has_punct = true;
        }
    }

    // 四个条件必须同时满足才返回true
    return has_upper && has_lower && has_digit && has_punct;
}

另外补充两点小细节:

  • 原代码的printf语句里缺少换行符\n,修复时已经补上
  • 使用else if不是必须的,但可以避免重复判断已经确认过的字符类型,稍微提高效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 14:01:26