我的C代码:
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
Run Code Online (Sandbox Code Playgroud)
为什么这个程序在输入方面会这样反应hello?
hello
hello
Run Code Online (Sandbox Code Playgroud)
而不是像:
hheelloo
Run Code Online (Sandbox Code Playgroud)
键入时,控制台会抓取键盘的输出,并将其回显给您.
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2164 次 |
| 最近记录: |