About Me

My photo
Raipur, Chhattisgarh, India
Hi , I am Amit Thakur. I have worked as a QA Engineer for two years and as a Java Developer for one year in NIHILENT TECHNOLOGIES PVT. LTD., Pune.Currently I am working as DEAN (Research & Development) in Bhilai Institute of Technology, Raipur.

Wednesday, September 4, 2013

C Program to Input Password for Validation of User name

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: