How to Input Password in C ?
#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]=''; printf("\nPassword Entered : %s",password); getch(); }
Output :
Enter password : ****** Password Entered : rakesh
Explain ?
ch=getch();
- Accept Character without Echo [ without displaying on Screen ]
- getch will accept character and store it in “ch”
if(ch==13) break;
- ASCII Value of “Enter Key” is 13
- Stop Accepting Password Characters after “Enter” Key.
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]
password[i++]=ch; ch='*';
- Store Accepted Character in String array .
- Instead of Displaying Character , display Asterisk (*)
No comments:
Post a Comment