我的C代码:
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}为什么这个程序在输入hello时会有这样的反应?
hello
hello而不是像:
hheelloo发布于 2011-06-21 22:25:55
当你打字时,一个控制台抓取来自键盘的输出,并将其回显给你。
getchar()对输入流进行操作,通常将输入流配置为打开“规范输入”。这样的配置减少了针对缓冲方案轮询输入所花费的CPU时间,其中输入被缓冲,直到发生通知缓冲器扩展的特定事件。按enter键(和按下control 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;
}发布于 2011-06-21 22:17:07
当您按enter时,您的终端可能只将您的输入写入到stdin。试着输入一些东西,退格键和写一些其他东西;如果你看不到最初输入的字符,这意味着你的终端正在等待你在将数据发送到程序之前组成行。
如果你想要原始的终端访问(例如,对按键和按键的反应),你应该尝试像ncurses这样的终端库。
发布于 2011-06-21 22:15:55
标准的输入/输出流可以缓冲,这意味着您的输入可能不会回显到屏幕上,直到遇到空格字符(例如)。
https://stackoverflow.com/questions/6426718
复制相似问题