#include<stdio.h>
#include<conio.h>
char pw[25],ch;
int i;
main()
{
printf("\n\nEnter password");
while(1)
{
if(i<0)
i=0;
ch=getch();
if(ch==13)
break;
if(ch==8)
{
putch('\b');
putch(NULL);
putch('\b');
-i;
continue;
}
pw[i++]=ch;
ch='*';
putch(ch);
}
pw[i]='\0';
printf("\n\n%s",pw);
getch();
}
This requirement usually means you want to ensure that casual passers-by cannot see what the user typed as a password by accident. This might be by turning off the echo (this is what Unix usually does) or by echoing asterisks or something similar instead of the actual characters entered by the user.
The C standard alone does not help here. You have to define the environment in which you are going to be running. The techniques used in a GUI application are different from those used in a command line application.
Many versions of Unix provide a getpass()
function, but it is not defined in POSIX. As mentioned, it saves the terminal mode, turns off echoing, reads characters (normally discarding anything after the 8th character) and then reinstates the terminal mode before returning.
精彩评论