【问题标题】:Get a string without displaying it on the console获取一个字符串而不在控制台上显示它
【发布时间】:2014-07-18 17:08:55
【问题描述】:

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

【问题讨论】:

  • 不在标准 C 中。就您所知,甚至可能没有控制台。
  • 也许看看 (n)curses,或者给出你的程序应该运行的平台。
  • 最接近任何标准的是getpass。有关可能的替代方案,请参阅此问题:stackoverflow.com/questions/1196418/…
  • [graphics] 在这里似乎是一个相当不合适的标签。找不到与控制台输入相关的内容?

标签: c graphics


【解决方案1】:

我猜你想禁用用户输入的回显字符。您可以通过使用<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;
}

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

【讨论】:

  • 是否使用Visual c的头文件?
  • 抱歉,这是针对 Unix 环境的。现在 C 语言很少用于 Windows,所以我认为你有 Linux 环境或类似的环境。 Windows 没有 (至少),也许你可以在这里找到一个等价物:stackoverflow.com/questions/933745/…
【解决方案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,&lt;https://stackoverflow.com/questions/6856635/hide-password-input-on-terminal&gt;

【讨论】:

    猜你喜欢
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2017-11-06
    • 2019-12-11
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多