无法弄清楚如何使用getchar();在C.

时间:2013-09-27 20:41:58

标签: c getchar

#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;
}

代码从第一个getchar();输入结果,然后退出而不等待更多输入。那是为什么?

4 个答案:

答案 0 :(得分:9)

首先,getchar()返回int,而不是char。这样它可以返回任何有效字符(对于CHAR_BIT为8的系统,值为0..255),另一个值(通常为-1)为EOF。

其次,当用户输入答案时,信息包含字符(Y或N,您希望)加上换行符。可能有领先的空白;可能会有垃圾。

所以,你的F可能会得到第一个角色; C读取换行符,而不是等待更多输入。

如果您想要读取行并依次处理每行,请使用fgets()读取行,并使用sscanf()来解析结果。或者使用函数来封装类似的处理,例如下面的get_answer()函数。

#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;
}

请注意,一般而言,换行符位于输出的末尾。您可以从提示消息中省略它们,以便输入与交互式会话中的提示出现在同一行。 调用代码并没有真正正确处理EOF - 在输入任何数据之前,用户触发EOF条件(例如键入 Control-D )。 get_answer()中的代码没问题; main()中的代码应该测试零回报。

答案 1 :(得分:6)

如果您只想处理一个字符,请在每个while后使用getchar()循环

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')
    ;

答案 2 :(得分:2)

这是因为当您按Enter键时,在回答第一个问题后,回车键将存储在下一个变量C中。 要纠正它,只需写另一个getchar来消耗额外的Enter。

应该是: -

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

{
char F,C;

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

getchar(); /* takes the enter key */

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

getchar(); /* takes the enter key */

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;
}

答案 3 :(得分:1)

When you enter a character ,it is stored in F,then when you press enter,it is stored in stdin buffer and when next getchar() comes it reads it's input from the stdin buffer ,for this use fflush(stdin) before every getchar() you use.