我的C代码:
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
为什么输入“hello”时,这个程序会有这样的反应?
hello
hello
而不是像这样:
hheelloo
我的C代码:
int c;
c = getchar();
while (c != EOF) {
putchar(c);
c = getchar();
}
hello
hello
hheelloo
您输入的是hello
而不是h
e
l
l
o
,对吗?
因此,您输入的内容将被缓冲,直到按下enter键。
当您输入时,控制台会获取键盘输出并将其回显给您。
getchar()
操作的是一个输入流,通常配置为打开“规范输入”。这种配置减少了 CPU 轮询输入所花费的时间,采用缓冲方案对输入进行缓冲,直到发生某些事件,这些事件会触发缓冲区扩展。按下回车键(和按下 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;
}
stdin
指向键盘时,默认情况下是行缓冲的。这意味着您只能看到完整的行,而不是单个字符。标准输入/输出流可以进行缓冲,这意味着您的输入可能不会被回显到屏幕上,直到遇到空格字符(例如)为止。
#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();
}
}