ANSI C无回声键盘输入

时间:2009-02-17 18:01:21

标签: c

我一直在谷歌搜索没有运气。我正在寻找一种方法来做getc()或gets()或任何不回应终端的方法。我看到了kbhit(),但这似乎不是ANSI的一部分。理想情况下,我希望代码看起来像

char s[100];
no_echo_gets(s); /* Won't echo to screen while being typed */
printf("%s\n", s);

有人知道一种良好的ANSI兼容方式吗?

8 个答案:

答案 0 :(得分:6)

对于类UNIX系统,您希望使用ECHO标志...

#include <termios.h>
...
struct termios t;
tcgetattr(fd, &t);
t.c_lflag &= ~ECHO;
tcsetattr(fd, TCSANOW, &t);
...

答案 1 :(得分:5)

getpass命令存在于Linux中。但你可以制作一个更漂亮的版本,单独的系统回声不会消除对enter命令的需要,而击倒缓冲并不会在数据输入后杀死carraige返回的产生。将两者结合起来可以很好地逼近一个安静的入口。您可以添加星号以提供秘密条目外观,因此以下是两个建议的组合:

    #include <stdio.h>
    #include <termios.h>
    #include <unistd.h>
    int getche(void);
    int main(int argc, char **argv){
    int i=0;       
    char d,c='h',s[6];
    printf("Enter five secret letters\n");
    s[5]='\0'; //Set string terminator for string five letters long
    do{
      d=getche();//Fake getche command silently digests each character
    printf("*");
      s[i++]=d;} while (i<5);
    printf("\nThank you!!\n Now enter one more letter.\n");
    c=getchar();
    printf("You just typed %c,\nbut the last letter of your secret string was %c\n",c,d);   
    printf("Your secret string was: %s\n",s);   
        return 0;
    }
    /* reads from keypress, echoes */
        int getche(void)
        {
            struct termios oldattr, newattr;
            int ch;
            tcgetattr( STDIN_FILENO, &oldattr );
            newattr = oldattr;
            newattr.c_lflag &= ~( ICANON | ECHO);\\knock down keybuffer
            tcsetattr( STDIN_FILENO, TCSANOW, &newattr );
            system("stty -echo");\\shell out to kill echo
            ch = getchar();
            system("stty echo");
            tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
            return ch;
        }

答案 2 :(得分:4)

您无法使用ANSI C以跨平台方式执行此操作。您必须使用某些特定于操作系统的代码,或使用ncurses等库。

答案 3 :(得分:2)

由于您的任务非常基础,如果您很幸运,您的系统将具有getpass()功能:

char * getpass(const char *prompt);

如果您不想要提示,请执行以下操作:

char *s = getpass("");
if (s != NULL)
    printf("Your password was %s!\n", s);
与所有与回声和缓冲相关的C函数一样,

getpass()是非标准的,但在Mac OS X上可能存在,可能是Linux,并且在GNU C库中列出,所以它可能出现在任何系统上使用glibc。

如前所述,ANSI和ISO标准 not 指定一种标准方式来读取输入而不回显,或读取无缓冲输入(即一次在字符上)。

答案 4 :(得分:2)

也许你可以尝试这样:

#include<stdio.h>
char s[100];
system("stty -echo");
scanf("%s",s); /* Won't echo to screen while being typed */
system("stty echo");
printf("You have entered:");
printf("%s\n", s);
return 0;
}

在Linux中,系统函数“stty -echo”是键入没有回声的sth。希望这会有所帮助。

答案 5 :(得分:0)

没有一个; ANSI C和ISO C ++都没有这样的东西。

答案 6 :(得分:0)

这取决于您的环境,而不是语言提供的内容。如果您打算进行广泛的字符模式I / O,您可能会查看像curses这样的库。否则,您必须手动操作终端或Windows控制台。

答案 7 :(得分:-1)

ANSI和ISO C没有定义此功能,但大多数C编译器都有getch()或接近变化。

您需要为您正在使用的每个编译器执行预处理器定义,该编译器具有不同的库和函数。这并不难,但你可能会认为这很烦人。

- 亚当

相关问题