Loop skips a scanf statement after the first time

2019-02-25 03:49发布

问题:

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.

回答1:

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].