Nautilus
Nautilus

Reputation: 81

Get password in console application using c with starred characters

I am going to develop a method to get password in command line and show * for each character , when user type password characters. my programming language is c and I like code with c too .
I try this code but it doesn't work and it doesn't hide password characters and doesn't end receiving password.

int i,j=1;
printf("Enter your PASSWORD : ");
while(j > 0)
{
    c=getch();
    if (c==13) j=0;
    else
    {
        password[i] = c;
        printf("*");
        i++;
    }
}
printf("You Entered %s ", password );
printf("as an PASSWORD");

Upvotes: 0

Views: 686

Answers (1)

Abhishek
Abhishek

Reputation: 2979

Well, I can't see any problem in your code except 'i' isn't initialized to 0 before being incremented. Here's a simplified version of your code which works.

    int i=0; char c, pass[101];
    printf("Enter your PASSWORD (100 Chars max): ");
    while(c!=13 && i<100){
        pass[i++]=c=getch();
        printf((c!=13)?"*":"\n");
    }
    pass[i--] = '\0';
    printf("\n\tYou Entered %s ", pass);

Upvotes: 1

Related Questions