获取字符串而不在控制台上显示它

时间:2014-07-18 17:08:55

标签: c graphics

我想从用户那里得到一个字符串(带空格),但我不希望它显示在控制台上。 C语言有什么方法可以实现吗?

2 个答案:

答案 0 :(得分:2)

您可以像这样实现自己的getch版本,然后屏蔽它。以下示例仅为了记录/测试目的而吐出输入。您可以通过移除printf来电来禁用该功能。

祝你好运!

代码清单


#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int getch();

int main(int argc, char **argv) {
   int ch;
   printf("Press x to exit.\n\n");
   for (;;) {
      ch = getch();
      printf("ch = %c (%d)\n", ch, ch);
      if(ch == 'x')
         break;
   }
   return 0;
}

int getch() {
   struct termios oldtc;
   struct termios newtc;
   int ch;
   tcgetattr(STDIN_FILENO, &oldtc);
   newtc = oldtc;
   newtc.c_lflag &= ~(ICANON | ECHO);
   tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
   ch=getchar();
   tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
   return ch;
}

示例运行


gcc test.c  && ./a.out


Press x to exit.

ch = a (97)
ch = b (98)
ch = c (99)
ch = 1 (49)
ch = 2 (50)
ch = 3 (51)
ch =
 (10)
ch =
 (10)
ch = x (120)

<强>参考


  1. 隐藏终端上的密码输入,已访问2014-07-18,<https://stackoverflow.com/questions/6856635/hide-password-input-on-terminal>

答案 1 :(得分:2)

我想您要禁用用户输入的 echoing 字符。您可以使用<termios.h>中的函数设置终端属性,如下所示:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>

#define MAX_LINE_SIZE 512

int main (int argc, char *argv[])
{
   /* get terminal attributes */
   struct termios termios;
   tcgetattr(STDIN_FILENO, &termios);

   /* disable echo */
   termios.c_lflag &= ~ECHO;
   tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios);

   /* read a line */
   char line[MAX_LINE_SIZE] = { 0 };
   fgets(line, sizeof(line), stdin);

   /* enable echo */
   termios.c_lflag &= ~ECHO;
   tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios);


   /* print the line */
   printf("line: %s", line);

   return 0;
}

上面的例子读取了一行(没有回显字符)然后它只是将行打印回终端。