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

如何判断变量是否等于指定字符串?C语言程序调试求助

问题分析与修正方案

你的代码存在多处关键错误,导致无法触发"info"判断逻辑,同时还有内存溢出、类型不匹配等问题,具体修正点如下:

1. 字符串存储与输入的错误

  • char name; 和 char input; 是单个字符变量,无法存储姓名、"info"这类完整字符串,必须改为字符数组,比如char name[50];(预留足够空间存姓名)、char input[10];(存输入指令)。
  • int age; 是整数类型,用scanf("%s", &age);读取会导致类型不匹配,应该用scanf("%d", &age);。
  • 字符数组作为scanf的参数时,数组名本身就是首地址,不需要加&。

2. 字符串比较的错误

C语言中不能直接用==比较字符串,因为==比较的是两个字符串的内存地址而非内容。必须使用标准库的strcmp()函数,使用前需包含头文件<string.h>,判断逻辑改为if(strcmp(input, "info") == 0)(strcmp返回0表示两个字符串内容完全一致)。

3. 输出格式的错误

输出年龄时用%s会导致格式错误,应使用%d对应int类型的age。


修正后的完整代码

#include <stdio.h>
#include <string.h>  // 引入strcmp所需的头文件

int main()
{
    char name[50];  // 字符数组存储姓名
    int age;

    printf("your name\n");
    scanf("%s", name);

    printf("your age\n");
    scanf("%d", &age);

    char input[10];
    scanf("%s", input);
    if(strcmp(input, "info") == 0)  // 用strcmp比较字符串内容
    {
        printf("%s\n", name);
        printf("%d\n", age);  // 用%d输出整数年龄
    }

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 17:37:03