循环在第一次之后跳过一个scanf语句 [英] Loop skips a scanf statement after the first time
问题描述
pre $ int $ $ $ $ $ $ $ $漂浮英亩[20];
浮动蒲式耳[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
字符选择;
int counter = 0;
(counter = 0; counter< 20; counter ++)
{
printf(你想进入另一个农场吗?
scanf(%c,& choice);
if(choice =='n')
{
printf(in break);
break;
}
printf(输入亩数:);
scanf(%f,& acres [counter]);
printf(输入蒲式耳数:);
scanf(%f,& bushels [counter]);
}
return 0;
$ b每次程序运行通过第一次scanf都能正常工作,
在%c之前添加一个空格在
scanf
中。在读取 choice
之前,这将允许 scanf
跳过任意数量的空格。
scanf(%c,& choice);
是唯一需要的更改。
$ b
在 scanf(%c,& choice)之前添加
也可以使用。 fflush(stdin);
;
如果 scanf(%c,& choice);
即使输入读缓冲区中只有一个字符 scanf
会将此字符解释为有效的用户输入并继续执行。不正确的使用scanf可能会导致一系列奇怪的错误[如在中使用无限循环,而
循环]。
Here is the code for main():
int main (void)
{
float acres[20];
float bushels[20];
float cost = 0;
float pricePerBushel = 0;
float totalAcres = 0;
char choice;
int counter = 0;
for(counter = 0; counter < 20; counter++)
{
printf("would you like to enter another farm? ");
scanf("%c", &choice);
if (choice == 'n')
{
printf("in break ");
break;
}
printf("enter the number of acres: ");
scanf("%f", &acres[counter]);
printf("enter the number of bushels: ");
scanf("%f", &bushels[counter]);
}
return 0;
}
Every time the program runs through the first scanf works fine but on the second pass through the loop the scanf to enter a character does not run.
Add a space before %c
in scanf
. This will allow scanf
to skip any number of white spaces before reading choice
.
scanf(" %c", &choice);
is the only change required.
Adding an fflush(stdin);
before scanf("%c", &choice);
will also work. fflush
call will flush the contents of input buffer, before reading the next input via scanf.
In case of scanf(" %c", &choice);
even if there is only a single character in the input read buffer, scanf
will interpret this character as a valid user input and proceed with execution. Incorrect usage of scanf may result in a series of strange bugs [like infinite loops when used inside while
loop].
这篇关于循环在第一次之后跳过一个scanf语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!