Reputation: 21
I was trying to make a program that inputs a password from a user and stores the password as the string entered by the user but the display should contain asterisks, using getch() function. i am bamboozled by this. If anyone could help?
Upvotes: 1
Views: 4646
Reputation: 9804
Assuming you are running on windows and your encoding is ASCII
Try this:
#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;
}
Upvotes: 2