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

为何scanf在for循环内无法正常工作?(字符输入场景)

逐个输入员工ID字符时scanf失效的原因与解决

问题代码

#include<stdio.h>
#include<stdlib.h>

int main() {
  int i, n;
  printf("Enter length of employee id:\n");
  scanf("%d", &n);
  char * arr = (char * ) malloc((n + 1) * sizeof(char));
  printf("Enter employee id:\n");

  //      scanf("%s", arr);
  for (i = 0; i < n; i++) {
    printf("Enter %dth character of employee id:\n", i + 1);
    scanf("%c", (arr + i));
  }

  for (i = 0; i < n; i++) {
    printf("%c", *(arr + i));
  }
}

运行现象(n=3时)

Enter length of employee id:
3
Enter employee id:
Enter 1th character of employee id:
Enter 2th character of employee id:
d
Enter 3th character of employee id:

d

失效原因

核心问题是输入缓冲区的换行符残留:

  • 用scanf("%d", &n)输入数字后,你按下的回车键对应的换行符(\n)会留在输入缓冲区中,没有被处理。
  • 第一个scanf("%c")会直接读取这个残留的换行符,不会等待你手动输入第一个字符,所以你看不到输入第一个字符的机会。
  • 当你输入第二个字符d并按下回车后,这个新的换行符又会被第三个scanf("%c")读取,同样跳过了第三个字符的输入步骤。
  • 最终数组中存储的是\n、d、\n,输出时就会显示空行、d、空行,和你看到的现象完全匹配。

修复方案

有两种简单的解决方式:

方式1:读取n后清空缓冲区

在scanf("%d", &n)之后,调用getchar()吃掉残留的换行符:

scanf("%d", &n);
getchar(); // 清除输入n后的换行符

方式2:在%c前加空格

修改scanf的格式串,在%c前添加一个空格,空格会自动跳过所有空白字符(包括换行、空格、制表符):

scanf(" %c", (arr + i)); // 注意%c前的空格

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 13:18:11