【问题标题】:How to have password echoed as asterisks using getch()如何使用 getch() 将密码回显为星号
【发布时间】:2013-06-16 07:00:41
【问题描述】:

我试图制作一个程序,该程序输入用户密码并将密码存储为用户输入的字符串,但显示应包含星号,使用 getch() 函数。我被这个迷惑了。如果有人可以帮忙?

【问题讨论】:

  • 你到现在为止做了什么来解决这个问题?展示你的努力。
  • 您的问题是特定于操作系统的。在 Linux 上,您可以尝试使用 ncurses

标签: c


【解决方案1】:

假设你在 windows 上运行并且你的编码是 ASCII
试试这个:

#include <stdio.h>
#include <string.h>
#include <conio.h>
int main()
{
    char buffer[256] = {0};
    char password[] = "password";
    char c;
    int pos = 0;

    printf("%s", "Enter password: ");
    do {
        c = getch();

        if( isprint(c) ) 
        {
            buffer[ pos++ ] = c;
            printf("%c", '*');
        }
        else if( c == 8 && pos )
        {
            buffer[ pos-- ] = '\0';
            printf("%s", "\b \b");
        }
    } while( c != 13 );

    if( !strcmp(buffer, password) )
        printf("\n%s\n", "Logged on succesfully!");
    else
        printf("\n%s\n", "Incorrect login!");
    return 0;
}

【讨论】:

  • 813 似乎是魔法常数。并非所有系统都是 ASCII 或 Windows。您应该将它们替换为 '\b''\n'(或 '\r')。
  • &lt;conio.h&gt; 是特定于 Windows 的。在 Linux 或 Posix 上不存在。
  • 你们俩完全正确!我在答案中添加了假设,直到 PO 指定他正在使用的环境:)
猜你喜欢
  • 2012-06-15
  • 2010-12-27
  • 2016-06-18
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多