Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indefinite for loop not working in C

Tags:

c

dev-c++

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;
}
like image 546
Finn Fuller Avatar asked Mar 24 '23 09:03

Finn Fuller


2 Answers

If we briefly run through your program, here's what will happen:

  1. It prompts the user to type a number.
  2. The user enters a number and presses enter.
  3. scanf reads the number, but leaves the newline in the queue.
  4. It prompts the user to type Y or N.
  5. 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.

like image 180
icktoofay Avatar answered Apr 21 '23 02:04

icktoofay


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.

like image 20
Kyle T Avatar answered Apr 21 '23 02:04

Kyle T