在类似的问题中,扫描程序读取字符或字符串时会跳过,因为它从输入缓冲区中"Enter"键在之前的扫描中被按下,但我不认为这是问题所在。如果input1是整数,这个程序不会跳过第二次扫描,但是对于其他类型的输入(double, char, string等),它会跳过第二次扫描。
#include <stdio.h>
#include <string.h>
int main(){
int input1;
char input2[6];
printf("Enter an integer. ");
scanf("%d", &input1);
printf("You chose %dn", input1);
printf("Write the word 'hello' ");
scanf(" %s", input2);
if (strcmp(input2,"hello")==0){
printf("You wrote the word hello.n");
} else {
printf("You did not write the word hello.n");
}
return 0;
}
为什么会发生这种情况?
代码注释:
int input1 = 0; // Always initialize the var, just in case user enter EOF
// (CTRL+D on unix) (CTRL + Z on Windows)
while (1) // Loop while invalid input
{
printf("Enter an integer. ");
int res = scanf("%d", &input1);
if ((res == 1) || (res == EOF))
{
break; // Correct input or aborted via EOF
}
int c;
// Flush stdin on invalid input
while ((c = getchar()) != 'n' && c != EOF);
}
printf("You chose %dn", input1);
另外,看看如何使用scanf
避免缓冲区溢出您是否试过写"%*c"在你的%c或%s或%d之后?像这样:scanf("%s%*c", input1);