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

C语言输入字符串匹配if语句报错:常量过长问题求助

解决C语言中输入字符串匹配报错“constant character is too long for its type”的问题

嘿,我一眼就看出问题出在哪了——你在处理字符串的时候犯了两个C语言新手常踩的坑,咱们一步步解决:

问题根源分析

  1. 变量类型错误:你声明的char b只能存储单个字符(比如'a'、'5'这种),但你要输入的是像danidev这样的多字符字符串,用单个char变量去存肯定会报“常量过长”的错误——编译器会把'danidev'当成一个不符合char存储规则的超长字符常量。
  2. 字符串比较方式错误:就算你把变量类型改对了,用==去比较两个字符串也是行不通的。在C语言里,==比较的是字符串数组的内存地址,而不是字符串的实际内容,要比较字符串内容得用标准库的strcmp()函数。

修正后的完整代码

#include <stdio.h>
#include <string.h>  // 必须包含这个头文件才能使用strcmp函数

void danidev(void){ 
    printf("Dani is a YouTuber and an indie game developer and an fps game developer having his game published in play store he is 22 years old and goes to a university\n"); 
}
void brackeys(void){ 
    printf("brackeys is a YouTuber and an indie game developer and also an fps game developer having most of his games published in itch.io and has a team which works on game development\n"); 
}
void blackthornprod(void){ 
    printf("They are two brothers who create video games and teach others how to do the same over on Youtube and Udemy! They are passionate in sharing their knowledge and game creation journey with other aspiring game developers.\n"); 
}
void jabrils(void){ 
    printf("jabrils is an ai programmer and also a machine learning pro coder and also a game developer he has made a lot of ai and has saved millions of people from their tough times\n"); 
}
void codingbullet(void){ 
    printf("coding bullet is a multi intelligent ai developer and also a master in machine learning also he owns a youtube channel with 2.06 million subscribers\n"); 
}

int main(){ 
    printf("HERE IS THE INFORMATION OF FAMOUS CODING YOUTUBERS (PLEASE TYPE THE FOLLOWING YOUTUBERS NAME): "); 
    char input[50];  // 用char数组存储输入的字符串,50的长度足够容纳目标用户名
    scanf("%s", input);  // 用%s读取无空格的字符串输入
    
    if(strcmp(input, "danidev") == 0){  // strcmp返回0表示两个字符串完全相等
        danidev(); 
    } else if(strcmp(input, "brackeys") == 0){ 
        brackeys(); 
    } else if(strcmp(input, "blackthornprod") == 0){ 
        blackthornprod(); 
    } else if(strcmp(input, "jabrils") == 0){ 
        jabrils(); 
    } else if(strcmp(input, "codingbullet") == 0){ 
        codingbullet(); 
    } else{ 
        printf("I don't know what you're talking about\n"); 
    } 
    return 0; 
}

关键修改点说明

  • 新增<string.h>头文件:strcmp()函数是这个头文件提供的,用来安全比较字符串内容。
  • 替换变量类型:把char b改成char input[50],创建一个长度为50的字符数组(如果担心长度不够,可以改成100),足够存储所有目标用户名。
  • 调整输入方式:用scanf("%s", input)读取输入,%s是C语言读取无空格字符串的标准格式符,会自动把输入内容存入数组。
  • 修正比较逻辑:把所有==替换为strcmp(),比如strcmp(input, "danidev") == 0表示输入字符串和目标字符串完全一致,此时执行对应函数。
  • 细节优化:修正了原代码里的拼写错误(比如FOLLWOING改成FOLLOWING),调整了输出格式让内容更易读。

现在编译运行这个代码,输入对应的用户名,就能得到正确的输出啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:07:30