c - C : why it won't print a character right after I use getchar? 中的 getchar() 函数

标签 c input inputstream getchar

我只是编程的初学者。我正在学习 K&R 的书《C 编程语言》。我一边看一边对这个问题越来越好奇—— 当有一个循环从输入中一个一个地获取字符时,我在循环中放置了一个输出函数,我认为其结果就像在输入每个字符后立即打印出来。但是结果好像是按了一个键电脑才打印出一整包字符。

如K&R书上练习1-22的答案:

/* K&R Exercise 1-22 p.34 
 *
 * Write a program to "fold" long input lines into two or more
 * shorter lines after the last non-blank character that occurs before the n-th
 * column of input.  Make sure your program does something intelligent with very
 * long lines, and if there are no blanks or tabs before the specified column.
 */

#include <stdio.h>

#define LINE_LENGTH 80
#define TAB '\t'
#define SPACE ' '
#define NEWLINE '\n'

void entab(int);

int main()
{
    int i, j, c;
    int n = -1;     /* The last column with a space. */
    char buff[LINE_LENGTH + 1];

    for ( i=0; (c = getchar()) != EOF; ++i )
    {
        /* Save the SPACE to the buffer. */
        if ( c == SPACE )
        {
            buff[i] = c;
        }
        /* Save the character to the buffer and note its position. */ 
        else
        {
            n = i;
            buff[i] = c;
        }

        /* Print the line and reset counts if a NEWLINE is encountered. */
        if ( c == NEWLINE )
        {
            buff[i+1] = '\0';
            printf("%s", buff);

            n = -1;
            i = -1;
        }
        /* If the LINE_LENGTH was reached instead, then print up to the last
         * non-space character. */
        else if ( i == LINE_LENGTH - 1 )
        {
            buff[n+1] = '\0';
            printf("%s\n", buff);

            n = -1;
            i = -1;
        }
    }
}

我想程序会变成这样,它只会打印出一行字符,长度为 80,就在我输入了 80 个字符之后(我还没有点击 ENTER 键)。但是,它不会以这种方式显示!不管有多少个字符,我完全可以输入整个字符串。当我最终决定完成这一行时,我只需点击 ENTER 键,它就会给我正确的输出:长字符串被切成几段/几行,有 80 个字符(当然最后一个可能包含更少超过 80 个字符)。

我想知道为什么会这样?

最佳答案

通常(在您的情况下),stdin 是行缓冲的,因此您的程序不会在键入字符时接收字符,而是在用户输入换行符 (< kbd>Return),或者,可能,当系统缓冲区已满时。

因此,当用户输入最终发送到您的程序时,它会被复制到程序的输入缓冲区中。这就是 getchar() 从中读取字符以填充 buff 的地方。

如果输入足够长,buff 会从输入缓冲区中填充LINE_LENGTH 个字符,然后打印几次(直到输入缓冲区的全部内容被消耗掉了)。

在 Linux 上(我认为通常是在 Unix-ish 系统上,但我不确定),您还可以通过键入 Ctrl+D 将输入发送到程序而无需输入换行符 在非空行上(作为一行中的第一个输入,关闭 stdin;在输入行的后面一点,您可以关闭 stdin通过键入两次),所以如果您在输入 LINE_LENGTH [或更多] 个没有换行符的字符后键入 Ctrl+D,[至少然后立即打印输入的初始部分。

关于c - C : why it won't print a character right after I use getchar? 中的 getchar() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14688637/

相关文章:

java - 如何将 BufferedImage 对象转换为 InputStream 或 BLOB?

ios - 避免 AppDelegate 中出现 "uncaughtExceptionHandler"警告

c - 使用 eclipse 和 cygwin 调试 C

javascript - 使用 jquery 删除循环内输入标签的禁用属性

python - 输入()错误 - NameError : name '...' is not defined

java - 从文件中读取整数值 (Java)

java - 如何将任何图像转换为 JPG?

c - gcc -O2 标志在修改 const int 时影响

c - 在 COM 嵌入式 IE 中设置 Accept-Language

java - 将多个用户输入存储到整数数组中