在C中有fgets()/ gets()/ scanf()时,scanf()有问题

Problem with scanf() when there is fgets()/gets()/scanf() after it in C

问题指出,如果scanf后跟fgets()/ gets()/ scanf(),它将是有效的输出。

fgets()/ gets()后跟scanf()

现场演示

1
2
3
4
5
6
7
8
9
#include<stdio.h>
int main() {
 int x;
 char str[100];
 scanf("%d", &x);
 fgets(str, 100, stdin);
 printf("x = %d, str = %s", x, str);
 return 0;
}

输出量

1
2
3
4
5
Input:
30
String
Output:
x = 30, str =

说明

fgets()和gets()用于在运行时从用户获取字符串输入。我以上
我们在运行代码时输入整数值,则它不会采用字符串值,因为
当我们在整数值之后输入换行符时,则fgets()或gets()将采用换行符
作为输入,而不是所需的" String"输入。

scanf()后跟一个scanf()

要反复获取scanf(),然后再获取scanf(),我们可以使用循环。

现场演示

1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
int main() {
 int a;
 printf("enter q to quit");
 do {
   printf("
enter a character and q to exit");
   scanf("%c", &a);
   printf("%c
", a);
 }while (a != 'q');
 return 0;
}

输出量

1
2
3
4
5
6
7
8
9
10
11
Input:
abq
Output:
enter q to quit
enter a character and q to exita
a
enter a character and q to exit
enter a character and q to exitb
b
enter a character and q to exit
enter a character and q to exitq

说明

在这里,我们可以看到在额外的新行之后有额外的行"输入一个字符并q退出",这是因为每次scanf()将一个换行符留在缓冲区中时,缓冲区中的下一个scanf()都会读取该换行符。要解决此问题,请使用'
'在scanf()中具有类型说明符,例如scanf("%c
");或者另一个选择是我们可以使用额外的getchar()或scanf()来读取额外的新行。