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

C语言结构体存储学生信息代码中fgets读取姓名未执行问题咨询

故障根因

问题出在C语言标准输入的缓冲区残留机制:
你用scanf_s搭配%d格式读取整数时,函数只会读取输入流中的数字字符,用户输完数字按下的回车对应的换行符\n会残留在stdin输入缓冲区中,不会被scanf_s处理。
当代码执行到标注为错误行的fgets时,fgets的特性是读取到换行符就立刻结束本次读取,因此它会直接读到缓冲区里残留的换行符立刻返回,完全不会等待用户输入新的名字,表现出来就是这行代码“没执行”,直接跳到了后续打印地址输入提示的语句。
你替换成gets、scanf/scanf_s读字符串时复现问题也是同一个原因,和读字符串的函数本身无关。
你观察到后续读address的fgets能正常执行,是因为读name的fgets已经把残留的换行符读走了,缓冲区为空,fgets就会正常等待用户输入地址;而进入下一轮循环时,scanf_s("%d")默认会自动跳过前导的空白字符(包括换行、空格),因此读取学号、年龄的逻辑不会受上一轮输入残留的换行影响,形成了“只有读name的fgets失效”的固定现象。

修复方案

方案1:清缓冲区+fgets(推荐,支持带空格的姓名/地址输入)

每次使用scanf_s读取完整数后,立刻写一段代码把输入缓冲区中残留的所有字符清空,直到读到换行符或输入结束,再调用fgets读字符串即可:

// 放在每个scanf_s("%d", &xxx) 语句之后执行
int tmp;
while ((tmp = getchar()) != '\n' && tmp != EOF);

另外fgets会把用户输入末尾的回车换行符也存到字符串里,打印时会多出不必要的空行,可以在fgets读完后手动去掉末尾的换行:

fgets(std[i].name, 30, stdin);
std[i].name[strcspn(std[i].name, "\n")] = '\0'; // 替换末尾换行为字符串结束符

对应修改后的输入段代码示例:

for (int i = 0; i < 3; i++)
{
    printf("Enter the roll number of the student:\n");
    scanf_s("%d", &std[i].roll_number);
    // 清缓冲区
    int tmp;
    while ((tmp = getchar()) != '\n' && tmp != EOF);

    printf("Enter the age of the student:\n");
    scanf_s("%d", &std[i].age);
    // 清缓冲区
    while ((tmp = getchar()) != '\n' && tmp != EOF);

    printf("Enter the name of the student:\n");  
    fgets(std[i].name, 30, stdin);
    std[i].name[strcspn(std[i].name, "\n")] = '\0';

    printf("Enter the address of the student:\n");
    fgets(std[i].address, 30, stdin);
    std[i].address[strcspn(std[i].address, "\n")] = '\0';
}

方案2:用scanf_s直接读字符串(仅适合无空格的输入场景)

scanf_s的%s格式会自动跳过前导的空白字符(包括残留的换行),不需要手动清缓冲区,但要注意传入缓冲区长度参数防止溢出,且该格式碰到空格就会停止读取,无法输入带空格的姓名、地址:

// 读name示例
printf("Enter the name of the student:\n");
scanf_s("%s", std[i].name, (unsigned)_countof(std[i].name));
额外代码问题提示

你代码中everoll函数的提示文本写错了,当前写的是Here are the names of students whose age is 14,和函数实际查询偶数roll number学生的功能不符,需要对应修改。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 07:57:08