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

为什么C语言中基于用户输入的if条件判断语句无法正常运行?

问题分析与解决

现有代码的错误点

  • scanf参数错误:question作为字符数组名,本身已经是首元素的地址,无需额外取地址&,原写法scanf("%s", &question)会触发类型不匹配,导致未定义行为。
  • 未限制输入长度,存在缓冲区溢出风险:你定义的question数组长度仅为4,刚好能存储yes\0,如果用户输入更长的字符串会越界覆盖其他内存空间,引发运行异常。

大小写不敏感判断的实现方法

引入<ctype.h>头文件,使用其中的tolower()函数把输入的每个字符转为小写,再和"yes"比较即可,不需要写多分支或判断。

修正后的完整代码

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

// 字符串转全小写工具函数
void str_tolower(char *str) {
    for (int i = 0; str[i] != '\0'; i++) {
        str[i] = tolower((unsigned char)str[i]);
    }
}

int main(){
    while (1){
        printf("Is Python a programming language? ");
        char question[4];
        // 限制最多读取3个字符,避免缓冲区溢出
        scanf("%3s", question);
        // 转小写后比较
        str_tolower(question);

        if (strcmp(question, "yes") == 0) {
            printf("Correct\n");
            // 答对后退出循环,如需要持续提问可删除该行
            break;
        } else {
            printf("Incorrect\n");
        }
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:45:02