gpt4 book ai didi

C程序: keyboard does not recognise enter using getch()

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:29 26 4
gpt4 key购买 nike

所以我试图用'*' 来隐藏我的密码。到目前为止,此代码适用于退格键和所有。但是,当我按下 Enter 键时,它根本没有执行任何操作,因此我无法继续执行该程序。

这是我目前所拥有的:

    printf("Password:");

fflush(stdout);
while((ch=mygetch()) != EOF || ch != 13 || z<sizeof(password)-1){
if(ch==127 && z>0){
printf("\b \b"); fflush(stdout);
z--; password[z] = '\0';
}
else if(isalnum(ch)){
putchar('*');
password[z++] = (char)ch;
}
}
password[z] = '\0';
printf("password: %s", password);

我在这个函数上定义了 mygetch:

    int mygetch(){
int ch;
struct termios oldt, newt;

tcgetattr (STDIN_FILENO, &oldt);
newt=oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr (STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

return ch;
}

我试着在里面放一个if-statement,那个if(ch==13) break;,它会打破while-loop。但是,它仍然没有做任何事情。键盘仍然无法识别回车键。它什么都不做。

如果我用&&替换所有的||,它会立即退出程序。

最佳答案

似乎换行符被假定为 CR (= 13)。但它可以是 LF (= 10)。请尝试在 while 循环中添加一个条件:

while((ch=mygetch()) != EOF || ch != 10 || ch != 13 || z<sizeof(password)-1) {

关于C程序: keyboard does not recognise enter using getch(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392164/

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