password protection code

in output,it is telling invalid password even though i hav entered right password(helloINDIA).

#include <stdio.h>
#include<string.h>
#include<conio.h>
void main()
{ 
char s1[20]="helloINDIA",s2[20],ch;
int i=0;
printf("enter password :\n");
while(ch!=13)    //ascii of enter key is 13
{
  ch=getch();
  s2[i]=ch;
  printf("*");
  i++;
}
s2[i]='\0';
if(strcmp(s1,s2)==0)
  printf(" password is valid");
else
  printf(" invalid password");

}
1 Like

Why not use scanf("%s", s2); to take the input string ? getch is highly unreliable and preferably be avoided. If you are intent on using getch() then i would suggest you try using fflush(stdin) before the getch while loop to flush the input buffer.

My guess is the problem is happening because there is a “\n” already present in the input buffer which scanf ,if used ,would have neglected but getch will input it and break from the loop. hence your string s2 becomes an empty string so you will get invalid password as output.

The ascii value of the enter key is not 13 , ‘\n’ corresponds to 10.
The problem is fixed by changing the order of your getch() statements.
This is my fix …since i have done it in linux it uses getchar() and dosent have conio.h.


#include <stdio.h>
#include<string.h>

void main()
{ 
char s1[20]="helloINDIA",s2[20],ch;
ch = 0;

int i=0;
printf("enter password :\n");
ch=getchar();
while(ch!=10)    //ascii of enter key is 10
{
  
  s2[i]=ch;
  printf("*");
  i++;
  ch=getchar();
}
s2[i]='\0';
if(strcmp(s1,s2)==0)
  printf(" password is valid");
else
  printf(" invalid password");

}


1 Like

void main()

{int j=3,i,n;

char pass1[5];

clrscr();

printf("\n\n\n\t\tEnter the Password: ");

scanf("%s",&pass1);

jump:if(strcmp(pass1,“helloINDIA”)==0)

{printf("\nValid Password!");}

else

{for(j=j;j>0;j–)

{printf("\n\tWrong! You Have now %d chances left",j);

}

scanf("%s",&pass1);

j–;

goto jump;

}}

getch();

}

//