Loop skips scanf instruction after first time

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 goes through the first scanf works fine, but the second time through the loop, scanf does not run for character input.

+3


source to share


1 answer


Add a space before %c

in scanf

. This will scanf

allow any number of spaces to be skipped before reading choice

.

scanf(" %c", &choice);

is the only change.



Adding a fflush(stdin);

before scanf("%c", &choice);

will also work. fflush

the call will clear the contents of the input buffer before reading the next input through scanf.

In case scanf(" %c", &choice);

, even if there is only one character in the read input buffer, it scanf

will interpret this character as valid user input and continue execution. Incorrect use of scanf can lead to a number of strange errors (eg infinite loops when used inside a loop while

).

+5


source







All Articles