cwhile-loopscanf

Stopping a while loop from user's input


I want to calculate average of the numbers entered by the user, where the user can enter as many numbers as he/she wants , i.e., the loop will stop only when the user wants.

To stop the loop from user's input, I tried this:

while (true)
{
    /* code here */
    printf("\nContinue? (Y/N)");
    char res;
    scanf("%c", &res);
    if (res == 'N') {
        break;
    }
}

I expect output like this:

Enter number: 32
Continue? (Y/N) Y
Enter number: 78
Continue? (Y/N) N
55.0000

But I am getting this output:

Enter number: 32
Continue? (Y/N)
Enter number: 78
Continue? (Y/N)
Enter number: N
Continue? (Y/N)
62.666668

Here is my full code:

#include <stdio.h>
#include <stdbool.h>
int main()
{
    int sum = 0;
    int count = 0;
    while (true) {
        printf("\nEnter number: ");
        int a;
        scanf("%d", &a);
        sum += a;
        count += 1;
        printf("\nContinue? (Y/N)");
        char res;
        scanf("%c", &res);
        if (res == 'N') {
            break;
        }
    }
    float avg = (sum*1.0)/count;
    printf("\n%f", avg);
    
    return 0;
}

I tried a lot to fix the issue myself, but with no luck. I am still unsure of where exactly is my fault. Please help me to fix this.


Solution

  • Your terminal is line buffered so the input buffer contains a number and a '\n'. scanf("%c", &reas) will read the newline. Change the format string to skip white space by prefixing the format string with a space ' ':

          scanf(" %c", &res);
    

    and example run:

    Enter number: 1
    
    Continue? (Y/N)Y
    
    Enter number: 2
    
    Continue? (Y/N)N
    
    1.500000
    

    You should check the return value from scanf() otherwise you may be operating on uninitialized variables.