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

C++验证密码含$时报错:指针与整数比较被禁止的问题

解决ISO C++ forbids comparison between pointer and integer的密码验证错误

我来帮你搞定这个编译错误,顺便纠正代码里的另一个逻辑坑:

1. 编译错误的根源

你看到的ISO C++ forbids comparison between pointer and integer错误,核心原因是类型不匹配:

  • x[i]是单个字符,类型为char(本质属于整数类型);
  • 你写的"$"是C风格字符串字面量,它的实际类型是const char*(一个指向字符的指针)。

C++不允许直接把指针和整数做比较,所以编译器直接抛出了这个错误。

2. 修复编译错误的方法

把双引号改成单引号,使用单个字符字面量'$'来做比较,这样类型就完全匹配了:

if(x[i] == '$') { dlr = 1; }

3. 代码里隐藏的逻辑错误

你最后判断密码是否有效的写法if(upr == lwr == dlr == num == 1)是错误的!在C++中,这个表达式会从左到右依次计算:比如先算upr == lwr得到一个bool值(0或1),再用这个结果和dlr比较,以此类推,这根本不是你想要的“四个条件都满足”的逻辑。

正确的写法应该用逻辑与运算符&&,确保四个标志位都为真:

if(upr && lwr && dlr && num) {
    cout << "The password is valid";
} else {
    cout << "The password is invalid";
}

4. 优化后的完整代码

我还帮你调整了几个细节,让代码更规范:

#include <iostream>
#include <string> // 替换C风格的<string.h>,C++操作std::string用这个头文件
#include <cctype> // 包含isupper/islower/isdigit的标准头文件

using namespace std;

int main () {
    string x("");
    cin >> x;
    bool upr = false;
    bool lwr = false;
    bool dlr = false;
    bool num = false;

    for(int i = 0; i < x.length(); i++) {
        // 转成unsigned char避免有符号char的未定义行为
        unsigned char c = static_cast<unsigned char>(x[i]);
        if(isupper(c)) {
            upr = true;
        }
        if(islower(c)) {
            lwr = true;
        }
        if(c == '$') {
            dlr = true;
        }
        if(isdigit(c)) {
            num = true;
        }
    }

    if(upr && lwr && dlr && num) {
        cout << "The password is valid";
    } else {
        cout << "The password is invalid";
    }

    cout << dlr;
    return 0;
}

额外细节说明

  • 替换<string.h>为<string>:前者是C语言的字符串操作头,C++中std::string的定义在<string>里;
  • 用unsigned char转换:因为isupper等函数要求参数是unsigned char或EOF,如果你的char是有符号类型,当字符值大于127时会变成负数,触发未定义行为;
  • 用false/true代替0/1:语义更清晰,符合C++的编码习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:25:00