我怎么能这样做,我可以在C++中显示星号(*)而不是纯文本的密码.
我要求输入密码,它在屏幕上显示通过.
如何将它们转换为星号(*),以便用户在输入时无法看到密码.
这就是我目前所拥有的
char pass[10]={"test"};
char pass1[10];
textmode(C40);
label:
gotoxy(10,10);
textcolor(3);
cprintf("Enter password :: ");
textcolor(15);
gets(pass1);
gotoxy(10,11);
delay(3000);
if(!(strcmp(pass,pass1)==0))
{
gotoxy(20,19);
textcolor(5);
cprintf("Invalid password");
getch();
clrscr();
goto label;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
您需要使用无缓冲的输入函数,如getch ()curses库提供的,或操作系统的控制台库.调用此函数将返回按下的键字符,但不会回显.您可以*在阅读每个字符后手动打印getch ().如果按下退格键,您还需要编写代码,并适当地更正插入的密码.
这是我用curses编写的代码.编译gcc file.c -o pass_prog -lcurses
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#define ENOUGH_SIZE 256
#define ECHO_ON 1
#define ECHO_OFF 0
#define BACK_SPACE 127
char *my_getpass (int echo_state);
int main (void)
{
char *pass;
initscr ();
printw ("Enter Password: ");
pass = my_getpass (ECHO_ON);
printw ("\nEntered Password: %s", pass);
refresh ();
getch ();
endwin ();
return 0;
}
char *my_getpass (int echo_state)
{
char *pass, c;
int i=0;
pass = malloc (sizeof (char) * ENOUGH_SIZE);
if (pass == NULL)
{
perror ("Exit");
exit (1);
}
cbreak ();
noecho ();
while ((c=getch()) != '\n')
{
if (c == BACK_SPACE)
{
/* Do not let the buffer underflow */
if (i > 0)
{
i--;
if (echo_state == ECHO_ON)
printw ("\b \b");
}
}
else if (c == '\t')
; /* Ignore tabs */
else
{
pass[i] = c;
i = (i >= ENOUGH_SIZE) ? ENOUGH_SIZE - 1 : i+1;
if (echo_state == ECHO_ON)
printw ("*");
}
}
echo ();
nocbreak ();
/* Terminate the password string with NUL */
pass[i] = '\0';
endwin ();
return pass;
}
Run Code Online (Sandbox Code Playgroud)
C++本身没有任何东西支持这一点.示例代码中的函数表明您正在使用curses或类似的东西; 如果是这样,检查cbreak和nocbreak功能.一旦你打电话cbreak,你就可以回复这些角色了,你可以回复你喜欢的任何东西(如果你愿意,你可以回音).
| 归档时间: |
|
| 查看次数: |
6515 次 |
| 最近记录: |