Indefinite for loop not working in C
c, dev-c++
Solution
If we briefly run through your program, here's what will happen:
- It prompts the user to type a number.
- The user enters a number and presses enter.
- `scanf` reads the number, but leaves the newline in the queue.
- It prompts the user to type Y or N.
- It tries to read a character, but does not skip any whitespace/newlines, so it ends up consuming the newline that was left 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.
Problem
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; } ```