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

C语言如何比较两个字符/字符串值?if判断不生效如何解决

C语言字符串比较逻辑不生效问题解决方案

问题根因

  • C语言中直接用==比较两个字符串时,实际对比的是两个字符串的首内存地址,而非字符串本身的内容:你的代码里marital是字符数组的首地址,"male"是字符串常量的首地址,二者地址永远不相等,所以if分支永远不会触发。
  • 额外的代码隐患:
    • scanf("%s",&marital);写法错误,数组名本身就代表首地址,不需要额外加取地址符&
    • 未做输入长度限制,输入超过4个字符时会发生数组越界,引发未定义行为
    • 标准C规范中main函数的返回值应为int而非void

修复方案

使用C标准库的strcmp函数完成字符串对比,该函数定义在<string.h>头文件中:

  • 两个字符串内容相等时,strcmp返回值为0
  • 第一个字符串字典序大于第二个时返回正整数,反之返回负整数

修改后完整代码

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

int main() {
    char marital[6]; // 多预留1位存储字符串结束符'\0',避免溢出
    printf("enter your marital details-");
    scanf("%5s", marital); // 限制最多输入5个字符,防止数组越界

    if(strcmp(marital, "male") == 0) {
        printf("you are insured");
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 04:06:02