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

C语言strcmp比较字符串不相等,输入数组含异常字符的问题

原因分析

  1. fgets()会读取换行符:当输入内容并按下回车时,fgets()会将输入的字符串**加上结尾的换行符(ASCII 10)**一起存入数组。如果输入时多打了空格,也会被一并存入。而预设的userName中没有这些额外字符,strcmp()逐字符比较时就会出现差异——比如你的案例中,输入多了一个空格,userInput第11位是空格(ASCII 32),userName第11位是字符串结束符\0(ASCII 0),差值为0-32=-32,和输出结果完全一致。

  2. 未初始化的数组残留垃圾值:userInput定义时未初始化,fgets()只会覆盖输入内容对应的字节,数组中未被覆盖的区域会保留内存里的原始随机值,这就是你看到的未预期符号(如16、89等)。而userName用字符串常量初始化,未使用的空间会自动填充\0,所以没有垃圾值。


解决方法

1. 移除fgets()读取的换行符

在调用fgets()后,用strcspn()快速定位换行符并替换为\0,截断多余的换行符:

fgets(userInput, 30, stdin);
// 替换换行符为字符串结束符
userInput[strcspn(userInput, "\n")] = '\0';

strcspn()会返回第一个匹配\n的索引位置,直接将该位置设为\0即可。

2. 初始化输入数组

定义userInput时直接初始化,确保未使用的数组空间默认填充\0,避免垃圾值:

char userInput[30] = {0};

3. 忽略输入首尾的空格(可选)

如果需要允许输入时带首尾空格,可以实现一个trim函数去除多余空格后再比较:

void trim(char *str) {
    // 去除开头空格
    while (*str == ' ') str++;
    // 去除结尾空格和换行符
    char *end = str + strlen(str) - 1;
    while (end > str && (*end == ' ' || *end == '\n')) end--;
    *(end + 1) = '\0';
}

调用fgets()后先执行trim(userInput),再进行比较。


修正后的示例代码

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

void trim(char *str) {
    while (*str == ' ') str++;
    char *end = str + strlen(str) - 1;
    while (end > str && (*end == ' ' || *end == '\n')) end--;
    *(end + 1) = '\0';
}

int main() {
    char userName[30] = "Alice Jane";
    char userInput[30] = {0};
    
    printf("Enter your text:\n");
    fgets(userInput, 30, stdin);
    trim(userInput);
    
    printf("Your text is: %s\n", userInput);
    printf("Real text is: %s\n", userName);
    
    int strComparing = strcmp(userName, userInput);
    if (strComparing == 0) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal, difference is %d\n", strComparing);
    }
    
    printf("Username size is %lu\n", sizeof(userName));
    printf("Inputed username size is %lu\n", sizeof(userInput));
    
    int i, j;
    for (i = 0; i < 30; i++) {
        printf("%d ", userName[i]);
    }

    printf("\nBreak between arrays\n");
    for (j=0; j < 30; j++) {
        printf("%d ", userInput[j]);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 07:45:35