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

使用fgets与switch处理字符的C语言计算器无法匹配case问题排查

问题分析与修复:C语言简易计算器switch不匹配分支的问题

你的代码存在两个核心问题,直接导致switch无法匹配到正确的case分支:

1. 数组越界访问

op数组定义为char op[80],它的有效索引范围是0到79。而你在switch中使用op[80],这属于访问超出数组边界的内存,是未定义行为,根本不可能读取到用户输入的运算符。

2. 未处理fgets读取的换行符

fgets会将用户输入时按下的换行符\n也读取到数组中,比如输入+后回车,op数组中存储的是"+\\n"。虽然直接取op[0]能拿到运算符,但如果不处理换行符,后续可能引发其他潜在问题。


修复后的代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h> // 用于处理字符串换行符

int main ()
{
    char s[80], op[80];
    int num1, num2, res;
    
    printf("Please type your operation:\n");
    // 读取第一个数字
    fgets(s, sizeof(s), stdin); 
    num1 = atoi(s); 
    // 读取运算符并去除换行符
    fgets(op, sizeof(op), stdin);
    op[strcspn(op, "\n")] = '\0'; // 截断换行符,确保op只保留运算符
    // 读取第二个数字
    fgets(s, sizeof(s), stdin);
    num2 = atoi(s);

    // 访问op数组的第一个元素(用户输入的运算符)
    switch (op[0]) {
        case '+' :
            res = num1 + num2;
            printf("%i\n", res);
            break;
        case '*' :
            res = num1 * num2;
            printf("%i\n", res);
            break;
        default:
            printf("不支持的运算符\n");
            return 1;
    }
    return 0;
}

额外优化建议

如果想让计算器支持更常规的输入方式(比如一次性输入10 + 20),可以改用scanf简化输入逻辑,避免多次调用fgets的繁琐:

#include <stdio.h>

int main ()
{
    int num1, num2, res;
    char op;
    
    printf("Please type your operation:\n");
    scanf("%d %c %d", &num1, &op, &num2);

    switch (op) {
        case '+' :
            res = num1 + num2;
            printf("%i\n", res);
            break;
        case '*' :
            res = num1 * num2;
            printf("%i\n", res);
            break;
        default:
            printf("不支持的运算符\n");
            return 1;
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:33:27