gpt4 book ai didi

c - 如何避免使用 getchar() 按下 Enter 来仅读取单个字符?

转载 作者:行者123 更新时间:2023-11-30 16:48:37 25 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 - 如何避免使用 getchar() 按下 Enter 来仅读取单个字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42885970/

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