Search code examples
cgetchar

Cannot figure out how to use getchar(); in C


#include <stdio.h>
int main(void)

{
    char F,C;

    printf("Do you have a Fever? y/n\n");
    F = getchar();

    printf("Do you have a runny nose or cough? y/n\n");
    C = getchar();


    printf("Here are the results you input:\n");
    printf("Do you have a fever?");
    putchar(F);

    printf("\nDo you have a runny nose or cough?");
    putchar(C);

    return 0;
}

The code inputs results from first getchar(); and then exits without waiting for more input. Why is that?


Solution

  • Use a while loop after each getchar() if you want to process only one character

    printf("Do you have a Fever? y/n\n");
    F = getchar();
    while((F = getchar()) != EOF && F != '\n') // This will eat up all other characters
        ;
    
    printf("Do you have a runny nose or cough? y/n\n");
    C = getchar();
    while((C = getchar()) != EOF && C != '\n')
        ;