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

user2824931 picture user2824931 · Sep 27, 2013 · Viewed 50.4k times · Source
#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?

Answer

Jonathan Leffler picture Jonathan Leffler · Sep 27, 2013

First, getchar() returns an int, not a char. This is so it can return any valid character (as a value 0..255 for systems where CHAR_BIT is 8) and a separate value (usually -1) as EOF.

Second, when users type an answer, the information contains the character (Y or N, you hope) plus a newline. There could be leading blanks; there could be trailing garbage.

So, your F probably gets the first character; the C reads the newline, not waiting for more input.

If you want to read lines and process each in turn, use fgets() to read the line and sscanf() to parse the result. Or use a function to encapsulate similar processing, such as the get_answer() function below.

#include <stdio.h>

extern int get_answer(void);    /* Declare in a header? */

int get_answer(void)
{
    int c;
    int answer = 0;
    while ((c = getchar()) != EOF && c != '\n')
    {
        if (answer == 0 && (c == 'y' || c == 'n'))  // Upper-case?
            answer = c;
        /* ?check for garbage here and complain? */
    }
    return answer;
}

int main(void)
{
    int F,C;

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

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

    printf("Here are the results you input:\n");
    printf("Do you have a fever? %c\n", F);
    printf("Do you have a runny nose or cough? %c\n", C);

    return 0;
}

Note that newlines go at the end of outputs, in general. You could omit them from the prompt messages so that the input appears on the same line as the prompt in an interactive session. The calling code does not really handle EOF properly — where the uses triggers an EOF condition (by typing Control-D for example) before entering any data. The code in get_answer() is OK; the code in main() should test for a zero return.