理论的getchar()和背后的putchar()函数 [英] Theory Behind getchar() and putchar() Functions

查看:181
本文介绍了理论的getchar()和背后的putchar()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过C程序设计语言的K&放工作; R和示例1.5难倒我:

I'm working through "The C Programming Language" by K&R and example 1.5 has stumped me:

#include <stdio.h>

/* copy input to output; 1st version */
int main(int argc, char *argv[])
{
    int c;

    while ((c = getchar()) != EOF)
        putchar(c);

    return 0;
}

据我所知,'的getchar()'需要一个字符'的putchar()'来显示。然而,当我在终端运行程序,那为什么我可以通过人物的整个行'的putchar()显示?

I understand that 'getchar()' takes a character for 'putchar()' to display. However, when I run the program in terminal, why is it that I can pass an entire line of characters for 'putchar()' to display?

推荐答案

由于您的终端是行缓冲。 的getchar()的putchar()仍然只对单个字符工作,但终端与提交字符的程序等待直到你输入一整行。然后的getchar()会从该缓冲区一个接一个,字符的putchar()显示它们一个接 - 酮

Because your terminal is line-buffered. getchar() and putchar() still only work on single characters but the terminal waits with submitting the characters to the program until you've entered a whole line. Then getchar() gets the character from that buffer one-by-one and putchar() displays them one-by-one.

加入:终端是行缓冲意味着它遇到一个换行符时提交输入程序。它通常是更有效的在一个时间提交数据,而不是一个字符的块。它还为用户提供了一个机会来编辑前行pressing进入。

Addition: that the terminal is line-buffered means that it submits input to the program when a newline character is encountered. It is usually more efficient to submit blocks of data instead of one character at a time. It also offers the user a chance to edit the line before pressing enter.

注意:行缓冲可以通过禁用规范模式被关闭终端并调用则setbuf NULL 标准输入

Note: Line buffering can be turned off by disabling canonical mode for the terminal and calling setbuf with NULL on stdin.

这篇关于理论的getchar()和背后的putchar()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆