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

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去消除缓冲区的问题。

回复
阅读 292
1 个回答

除了 %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.

......

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏