Possible Duplicate:
Hide password input on terminal
我想实现这个:
$Insert Pass:
User types: a (a immediately disappears & '*' takes its position on the shell)
On the Shell : a
Intermediate O/P: *
User types: b (b immediately disappears & '*' takes its position on the shell)
On the Shell : *b
Intermediate O/P: **
User types: c (c immediately disappears & '*' takes its position on the shell)
On the Shell : **c
Final O/P : ***
我尝试过以下方法:
#include <stdio.h>
#include <string.h>
#define SIZE 20
int main()
{
char array[SIZE];
int counter = 0;
memset(array,'0',SIZE);
while ((array[counter]!='\n')&&(counter<=SIZE-2))
{
array[counter++] = getchar();
printf("\b\b");
printf ("*");
}
printf("\nPassword: %s\n", array);
return 0;
}
但是我无法实现预期的输出。此代码无法使用户键入的字符不可见并立即显示“*”。
有人可以指导我吗?
谢谢。
最诚挚的问候, 桑迪普·辛格
最佳答案
你的方法不起作用;即使您可以覆盖该字符,我也可以在 script(1)
等工具中运行您的命令并查看输出。
正确的解决方案是将终端从“cooked”模式切换为“raw”模式并关闭回显。
第一个更改将使您的程序看到键入的每个字符(否则,shell 将收集一行输入并在用户按下 Enter 键后将其发送到您的进程)。
第二个更改阻止 shell/终端打印用户键入的内容。
See this article如何做到这一点。
关于c - 如何在 C 中为密码的每个输入字符显示 * - 使字符不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929734/