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

C语言输入判断if语句失效求助:输入James时为何无法触发对应输出?

为什么输入"James"时if语句不触发?

哈哈,这个坑我当初学C的时候也踩过!咱们先拆解问题出在哪:

你用fgets()读取输入的时候,它会把你按下回车键的那个**换行符\n**也一起存到first_name数组里。也就是说,当你输入"James"然后回车,first_name里实际存储的是"James\n",而你用strcmp()和"James"比较,这两个字符串肯定不相等,所以if条件永远不成立,自然不会打印那句"Hey ! Another James"。

解决方法

这里有两种常用的修复方式:

方法1:去掉fgets()读取的换行符

可以用strcspn()函数快速去掉换行符,在fgets()之后加一行代码就行:

first_name[strcspn(first_name, "\n")] = '\0';

strcspn()会返回字符串中第一个\n的位置,我们把这个位置的字符替换成字符串结束符'\0',就相当于把换行符删掉了。

方法2:用scanf()代替fgets()(适合单字名字)

如果你不需要处理带空格的名字,也可以直接用scanf()读取,它不会把换行符读进去:

scanf("%29s", first_name);

注意这里要写%29s,因为你的数组长度是30,留一个位置给'\0',避免缓冲区溢出。

修改后的完整代码(方法1示例)

#include <stdio.h>
#include <string.h>
int main (int argc, char** argv) {
    char first_name[30];
    printf(" Please enter your first name : ");
    fgets(first_name, 30 , stdin);
    // 去掉换行符
    first_name[strcspn(first_name, "\n")] = '\0';
    if (strcmp(first_name, "James") == 0)
        printf("Hey ! Another James \n");
    else
        printf("Goodbye!\n");
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 10:49:05