getchar和putchar

我的C代码:

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

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

 hello hello 

而不是像:

 hheelloo 

你的输入是hello而不是对吗?

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

键入时,控制台会从键盘上获取输出,并将其回显给您。

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

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

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

如果你想要原始终端访问(例如对按键和键盘的反应),你应该尝试一些终端库,如ncurses

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

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

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

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

 #include  #include  #include  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(); } }