C语言 不知道如何使用 getchar(); 在 C

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19059730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:34:05  来源:igfitidea点击:

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

cgetchar

提问by user2824931

#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?

代码首先输入结果getchar();,然后不等待更多输入就退出。这是为什么?

回答by Jonathan Leffler

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.

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

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.

其次,当用户输入答案时,信息包含字符(您希望是 Y 或 N)加上换行符。可能有前导空格;可能有尾随垃圾。

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

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

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.

如果要读取行并依次处理,请使用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;
}

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-Dfor example) before entering any data. The code in get_answer()is OK; the code in main()should test for a zero return.

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

回答by haccks

Use a whileloop after each getchar()if you want to process only one character

如果您只想处理一个字符,请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')
    ;

回答by Abhishek

It's because when you press Enter, after answering the first question, the enter key gets stored in the next variable C. To correct it just write another getchar to eat up the extra Enter.

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

It should be :-

它应该是 :-

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

回答by arvind

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.

当你输入一个字符时,它存储在 F 中,然后当你按下 Enter 时,它存储在 stdin 缓冲区中,当下一个 getchar() 到来时,它从 stdin 缓冲区读取它的输入,为此在每个 getchar 之前使用 fflush(stdin) () 你用。