I have the following code lines :
printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}
printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}
the code works but when I'm putting an input to x in the following form "1 1" (1 then space then 1 again) it put the 2nd 1 into y. How can I make it won't happen? it should just stop the code.
I know there are other methods to get inputs but as for now, I'm only allowed to use scanf to get input from the user.
答案 0 :(得分:0)
您正在看到scanf
的正常行为。第二个1被读取
第二个scanf
因为%d
会跳过空格,直到找到下一个数字为止
转换。
在第一个scanf
之后,这是输入缓冲区中剩下的内容
+-----+-----+------+
| ' ' | '1' | '\n' |
+-----+-----+------+
因此,如果您想在第一次转换后停止,则需要清除缓冲区。 您可以使用此功能:
void clear_line(FILE *fp)
{
if(fp == NULL)
return;
int c;
while((c = fgetc(fp)) != '\n' && c != EOF);
}
然后你可以这样做:
printf("enter a number: \n");
if (scanf("%d", &x) == 1)
{ //do some stuff}
else {return 1;}
clear_line(stdin);
printf("enter another number: \n");
if (scanf("%d",&y) == 1)
{ //do some stuff}
else {return 1;}
clear_line(stdin);
在这种情况下,即使您输入1 1
,第二个scanf
也会等待用户
输入