I'm currently reading Beginning C by Ivor Horton. Anyways my indefinite for
is printing my printf
statement twice before moving on. I'm sure I'm doing something wrong but I copied the code right from the book. I'm using Dev-C++ if that matters. Here is the code... Thanks
#include <stdio.h>
#include <ctype.h> // For tolower() function //
int main(void)
{
char answer = 'N';
double total = 0.0; // Total of values entered //
double value = 0.0; // Value entered //
int count = 0;
printf("This program calculates the average of"
" any number of values.");
for( ;; )
{
printf("\nEnter a value: ");
scanf("%lf", &value);
total+=value;
++count;
printf("Do you want to enter another value? (Y or N): ");
scanf("%c", &answer);
if(tolower(answer) == 'n')
break;
}
printf("The average is %.2lf.", total/count);
return 0;
}
If we briefly run through your program, here's what will happen:
scanf
reads the number, but leaves the newline in the queue.Obviously, we need to skip over the newline. Fortunately, that's rather easy, if non-obvious: add a space to the start of the format string, e.g.:
scanf(" %c", &answer);
A space in the format string means “skip as much whitespace as possible before reading the next thing”. This is done automatically for most conversions, but not for strings or characters.
Change this line
scanf("%c", &answer);
to
scanf(" %c", &answer);
The space will cause scanf to ignore whitespace preceding the character you enter.
The whitespace is a consequence of striking Enter after providing the number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With