关于scanf输入的缓冲区问题?

作者站长头像
站长
· 阅读数 17
int a = 0;
int b = 0;
char c = 'a';
char arr[20] = { 0 };
scanf("%d", &a);
//int ch1 = getchar();
scanf("%d", &b);
int ch2 = getchar();
scanf("%c", &c);
//int ch3 = getchar();
scanf("%s", arr);
printf("%d\n", a);
printf("%d\n", b);
printf("%c\n", c);
printf("%s\n", arr);

为什么只需要一个getchar就可以消除这个代码的缓冲区问题呢?我的理解是每次使用完scanf就需要使用一次getchar去消除缓冲区的问题。

回复
1个回答
avatar
test
2024-07-12

除了 %c ,问题里其它的都会自动跳过空白字符


http://port70.net/~nsz/c/c11/...

7 A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:

8 Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier.

......

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容