C : getchar() 和 putchar()

Arm*_*ure 2 c

所以我一直在自学 C 并且我遇到了来自“stdio.h”的“getchar()”和“putchar()”方法。据我了解,'getchar()' 从文本流中获取最新的字符并将其存储到一个变量中,而 'putchar()' 获取这个变量并将其打印到终端。

所以我写了下面的一段代码:

    #import<stdio.h>

void main () {
    printf("Enter a character and it will be repeated back to you:\n");
    int c;
    while (c != EOF) {
        c = getchar();
        printf("You entered : ");
        putchar(c);
        printf("\n");
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望它读取键盘输入并将其打印到屏幕上,一次一个字符。例如,如果我输入“home”,输出将是:

您输入了:h 您输入了:o 您输入了:m 您输入了:e

但我得到:

home 您输入了:h 您输入了:o 您输入了:m 您输入了:e

字符在输入时打印,然后重复。我不太确定我在这里做错了什么,或者我做错了什么,只是不太了解这个概念。谁能解释一下这里发生了什么?

Bar*_*mar 7

您得到的输出是预期的。

除非您使用特定于操作系统的功能来更改终端设置,否则终端输入仅在您输入整行时才可用于应用程序。终端驱动程序缓冲行以允许您在提交之前进行编辑,并在您键入时回显您的输入。

输入该行后,每次调用都会getchar()从该行(以及最后一个换行符)中检索一个字符。

然而,就是在你的程序无关你的问题的错误。您在c第一次分配之前进行测试。此外,该c != EOF测试正在检查上一次迭代的输入,该迭代已经尝试打印该输入,但您无法打印EOF.

编写循环的更好方法是:

while ((c = getchar()) != EOF) {
    printf("You entered : ");
    putchar(c);
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

或者,如果组合作业和测试令人困惑,您可以执行以下操作:

while (1) {
    c = getchar();
    if (c == EOF) {
        break;
    }
    puts("You entered: ");
    putchar(c);
    putchar('\n');
}
Run Code Online (Sandbox Code Playgroud)