getchar和putchar

时间:2011-06-21 14:12:33

标签: c getchar

我的C代码:

int c;
c = getchar();

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

为什么这个程序在输入hello时会这样反应?

hello
hello

而不喜欢:

hheelloo

6 个答案:

答案 0 :(得分:5)

您的输入是hello而不是h e l l o对吗?

因此,您输入的输入将被缓冲,直到您按输入

答案 1 :(得分:5)

当您键入时,控制台会抓取键盘的输出,并将其回显给您。

getchar()对输入流进行操作,输入流通常配置为打开“Canonical input”。这样的配置减少了用于缓冲​​输入的缓冲方案的输入轮询的CPU时间,直到发生使缓冲器扩展的某些事件。按下回车键(并按下控制器D)都会冲洗该缓冲区。

#include <unistd.h>

int main(void){   
    int c;   
    static struct termios oldt;
    static struct termios newt;

    /* Fetch the old io attributes */
    tcgetattr( STDIN_FILENO, &oldt);
    /* copy the attributes (to permit restoration) */
    newt = oldt;

    /* Toggle canonical mode */
    newt.c_lflag &= ~(ICANON);          

    /* apply the new attributes with canonical mode off */
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);


    /* echo output */
    while((c=getchar()) != EOF) {
        putchar(c);
        fflush(STDOUT_FILENO);
    }                 

    /* restore the old io attributes */
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);


    return 0;
}

答案 2 :(得分:3)

当您按Enter键时,您的终端可能只会将您的输入写入标准输入。尝试输入内容,退格并写下其他内容;如果您没有看到最初输入的字符,则表示您的终端在将数据发送到程序之前等待您撰写该行。

如果您想要原始终端访问(例如对按键和按键操作做出反应),您应该尝试一些终端库,如 ncurses

答案 3 :(得分:1)

标准输入/输出流可以缓冲,这意味着在遇到空白字符(例如)之前,您的输入可能不会回显到屏幕。

答案 4 :(得分:1)

因为stdin引用键盘时的默认值是行缓冲的 这意味着你只能看到整行,而不是单个字符。

想象一下,你问你的朋友他的电话号码是什么......但他必须把它写在一张纸上。当他写下这些数字时,你不会逐位获得数字:当他给你那张纸时,你得到所有的数字:)

答案 5 :(得分:0)

getchar从输入流中读取输入,只有在按下ENTER键后才能输入。在此之前,您只能看到控制台的回显结果。为了达到您想要的结果,您可以使用类似这样的结果

#include <stdio.h>
#include <termios.h>
#include <unistd.h>

int getCHAR( ) {
    struct termios oldt,
                 newt;
    int            ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    putchar(ch);
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}
void main() {
    int c;
    c = getCHAR();
    while (c != 'b') {
        putchar(c);
        c = getCHAR();
    }
}
相关问题