TransWikia.com

Condition not executed properly when using getchar()

Stack Overflow Asked on December 30, 2021

When I use getchar in this code, the output doesn’t run correctly and consecutively!

#include <stdio.h>
#include <conio.h>

int main()
{
    int i, sum=0, num;
    float ave;
    const int n = 5;
    clrscr();

    for(i = 0 ; i < n; i++) {
        printf ("Enter number %d: ", i+1);
        num = getchar();
        sum += num;
    }

    ave = (float) sum / n;
    printf("nThe average is: %6.2f", ave);
    getch();
    return 0;
}
Output:

Enter number 1: 1
Enter number 2: Enter number 3: 2
Enter number 4: Enter number 5: 3
The average is: 34.00

One Answer

getchar is a buffered function that holds the newline in the buffer. Correct code would be:

#include <stdio.h>

int main()
{
    int i, sum=0, num;
    float ave;
    const int n = 5;
    for(i = 0 ; i < n; i++) {
        printf ("Enter number %d: ", i+1);
        num = getchar();
        getchar(); // Eat the buffered input
        sum += num;
    }
    ave = (float) sum / n;
    printf("nThe average is: %6.2f", ave);
    getchar();
    return 0;
}

(I don't have Windows and conio.h), but it should be the same. The extra call to getchar is for 'eating' the buffered newline.

Answered by Ilian Zapryanov on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP