C Program to Input Password for Validation of User name
How to Input Password in C ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include<stdio.h> #include<conio.h> void main() { char password[25], ch; int i; clrscr(); puts("Enter password : "); while (1) { if (i < 0) { i = 0; } ch = getch(); if (ch == 13) break; if (ch == 8) /*ASCII value of BACKSPACE*/ { putch('b'); putch(NULL); putch('b'); i--; continue; } password[i++] = ch; ch = '*'; putch(ch); } password[i] = '\0'; printf("\nPassword Entered : %s", password); getch(); } |
Output :
1 2 | Enter password : ****** Password Entered : rakesh |
Explain ?
1 | ch=getch(); |
- Accept Character without Echo [ without displaying on Screen ]
- getch will accept character and store it in “ch”
1 2 | if(ch==13) break; |
- ASCII Value of “Enter Key” is 13
- Stop Accepting Password Characters after “Enter” Key.
1 2 3 4 5 6 7 8 | if(ch==8) /*ASCII value of BACKSPACE*/ { putch('b'); putch(NULL); putch('b'); i--; continue; } |
- ASCII Value of “BACKSPACE” is 8
- After hitting “backspace”following actions should be carried out -
- Cursor Should be moved 1 character back.
- Overwrite that character by “NULL”.
- After Writing NULL again cursor is moved 1 character ahead so again move cursor 1 character back .
- Decrement Current Track of Character. [i]
1 2 | password[i++]=ch; ch='*'; |
- Store Accepted Character in String array .
- Instead of Displaying Character , display Asterisk (*)