【发布时间】:2013-06-16 07:00:41
【问题描述】:
我试图制作一个程序,该程序输入用户密码并将密码存储为用户输入的字符串,但显示应包含星号,使用 getch() 函数。我被这个迷惑了。如果有人可以帮忙?
【问题讨论】:
-
你到现在为止做了什么来解决这个问题?展示你的努力。
-
您的问题是特定于操作系统的。在 Linux 上,您可以尝试使用
ncurses
标签: c
我试图制作一个程序,该程序输入用户密码并将密码存储为用户输入的字符串,但显示应包含星号,使用 getch() 函数。我被这个迷惑了。如果有人可以帮忙?
【问题讨论】:
ncurses
标签: c
假设你在 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;
}
【讨论】:
8 和 13 似乎是魔法常数。并非所有系统都是 ASCII 或 Windows。您应该将它们替换为 '\b' 和 '\n'(或 '\r')。
<conio.h> 是特定于 Windows 的。在 Linux 或 Posix 上不存在。