- Write a program in C to read a string as password from user, without showing it on screen.
- How to take a password as input from user in C programming language.
Here are the list of tasks we have to perform while reading password string:
- We should read characters without displaying them on screen. Instead we have to display '*' character.
- We should read input till user presses enter key.
- When user presses Backspace key, we should perform following actions:
- Remove his last entered character from input string.
- Move cursor back 1 character position and delete last star character from screen.
C program to read password string as input from user.
#include<stdio.h> #include<conio.h> int main() { char password[128], c; int index = 0; printf("Enter Password : "); /* 13 is ASCII value of Enter key */ while((c = getch()) != 13){ if(index < 0) index = 0; /* 8 is ASCII value of BACKSPACE character */ if(c == 8){ putch('\b'); putch(NULL); putch('\b'); index--; continue; } password[index++] = c; putch('*'); } password[index] = '\0'; printf("\nPassword String = %s", password); return 0; }Output
Enter Password : ****** Password String = asdfgh