gpt4 book ai didi

c - 如何避免按 Enter 和 getchar() 只读取单个字符?

转载 作者:太空狗 更新时间:2023-10-29 16:16:13 26 4
gpt4 key购买 nike

在接下来的代码中:

#include <stdio.h>

int main(void) {
int c;
while ((c=getchar())!= EOF)
putchar(c);
return 0;
}

我必须按 Enter 打印我用 getchar 输入的所有字母,但我不想这样做,我想做的是按这封信并立即看到我重复介绍的那封信,而无需按 Enter。例如,如果我按下字母“a”,我想在它旁边看到另一个“a”,依此类推:

aabbccddeeff.....

但是当我按下 'a' 时没有任何反应,我可以写其他字母,并且只有当我按下 Enter 时才会出现副本:

abcdef
abcdef

我该怎么做?

我在Ubuntu下使用命令cc -o example example.c编译。

最佳答案

这取决于您的操作系统,如果您在类似 UNIX 的环境中,ICANON 标志默认启用,因此输入会被缓冲,直到下一个 '\n'EOF。通过禁用规范模式,您将立即获得字符。这在其他平台上也是可能的,但没有直接的跨平台解决方案。

编辑:我看到您指定使用 Ubuntu。我昨天刚刚发布了类似的内容,但请注意,这将禁用您终端的许多默认行为。

#include<stdio.h>
#include <termios.h> //termios, TCSANOW, ECHO, ICANON
#include <unistd.h> //STDIN_FILENO


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

/*tcgetattr gets the parameters of the current terminal
STDIN_FILENO will tell tcgetattr that it should write the settings
of stdin to oldt*/
tcgetattr( STDIN_FILENO, &oldt);
/*now the settings will be copied*/
newt = oldt;

/*ICANON normally takes care that one line at a time will be processed
that means it will return if it sees a "\n" or an EOF or an EOL*/
newt.c_lflag &= ~(ICANON);

/*Those new settings will be set to STDIN
TCSANOW tells tcsetattr to change attributes immediately. */
tcsetattr( STDIN_FILENO, TCSANOW, &newt);

/*This is your part:
I choose 'e' to end input. Notice that EOF is also turned off
in the non-canonical mode*/
while((c=getchar())!= 'e')
putchar(c);

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


return 0;
}

您会注意到,每个字符出现两次。这是因为输入会立即回显到终端,然后您的程序也会使用 putchar() 将其放回。如果要取消输入与输出的关联,还必须关闭 ECHO 标志。您只需将适当的行更改为:

newt.c_lflag &= ~(ICANON | ECHO); 

关于c - 如何避免按 Enter 和 getchar() 只读取单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1798511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com