You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

C语言if语句中strcmp字符串比较失效,求问题原因及解决方法

问题分析与修正方案

嘿,我来帮你梳理代码里的问题,主要有三个关键错误需要调整:

  • strcmp的逻辑搞反了
    C语言里的strcmp函数,当两个字符串完全相等时返回0,不相等时返回非0值。你现在的if (strcmp(inputUnit, "in"))条件,会在输入的字符串不是"in"的时候执行代码块,这和你想要的“匹配到in就执行转换”的逻辑正好相反。正确的写法应该是判断返回值是否等于0:

    if (strcmp(inputUnit, "in") == 0)
    
  • 字符串缓冲区长度不足
    你定义的char inputUnit[2];只能容纳1个有效字符加上字符串结束符\0,但"in"是两个字符,加上\0需要至少3个字节的空间。如果输入"in",会导致缓冲区溢出,触发未定义行为(程序可能崩溃或者出现奇怪的结果)。所以要把数组长度改成3:

    char inputUnit[3];
    
  • return语句的位置错误
    你的return (0);写在了main函数的大括号外面,这是语法错误,编译器会报错。需要把它移到main函数内部的末尾,也就是闭合大括号}之前。

修正后的完整代码

#include <stdio.h>
#include <string.h>
char inputUnit[3];
float inputValue, returnValue;
int main() {
    printf("Enter value to convert: ");
    scanf("%f", &inputValue);
    printf("Enter unit to convert: ");
    scanf("%s", inputUnit);
    if (strcmp(inputUnit, "in") == 0) {
        returnValue = inputValue * 2.54;
        printf("%.2f %s = %.4f cm\n", inputValue, inputUnit, returnValue);
    }
    return (0);
}

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

火山引擎 最新活动