Learn Programming C | C++ | Java | Android | Tips and Tricks

How to Input Password in C : Validation of User name

Article Viewed : 505 times. No Comments

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]='\0';
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 (*)

About The Author

My name is Pritesh Taral. I am working in well known MNC. as Java Developer. I am part time blogger loves writing articles on C/C++. I am active on facebook using community fan page .One can Visit me @ Facebook Facebook Fan Page