Search code examples
arrayscfunctionif-statementdecrement

What is the problem in this code when I run the code it does not give the desired output


#include<stdio.h>
#include<string.h>
#include<conio.h>
int main()
{
char pwd[5];
int i;
printf("Enter your password: ");
for(i=0;i<=3;i++)
{
pwd[i]=_getch();
printf("%c",pwd[i]);
 if(pwd[i]==8)
  {
    if(i>0)
    {
    printf(" \b");
    i--;
    continue;
    }
    else
        break;
  }
}
pwd[i]='\0';
if(strcmp(pwd,"abcd")==0)
{
printf("\nPassword is correct");
}
else
{
printf("\nPassword is not correct");
}
return 0;
}

I want output in such form that when the user press backspace the previous character should be deleted and the user should be allowed to re-enter the previous character but this code has some problems in it. It deletes the previous character but doesn't allow to re-enter previous corrected character instead it takes it as next character what is the problem with this code please explain?


Solution

  • There is a bug in this code. At the 18th line inside the if (i > 0) statement, you are reducing the value of variable i by 1, which is alright. But then, you are not "reinputting" pwd[i]. And remember that adding '\b' to your string doesn't remove the previous character of it. It rather "adds" a new character, but you were outsmarted by the output. So here is a working code with the bug fixed:

    #include<stdio.h>
    #include<string.h>
    #include<conio.h>
    int main()
    {
        char pwd[5];
        int i;
        printf("Enter your password: ");
        for(i=0; i<=3; i++)
        {
            label:
            pwd[i]=_getch();
            printf("%c",pwd[i]);
            if(pwd[i]==8)
            {
                if(i>0)
                {
                    printf(" \b");
    
                    i--;
                    goto label;
                    continue;
                }
                else
                    break;
            }
        }
        pwd[i]='\0';
        if(strcmp(pwd,"abcd")==0)
        {
            printf("\nPassword is correct");
        }
        else
        {
            printf("\nPassword is not correct");
        }
        return 0;
    }
    

    I think this is enough explanation from me. The rest is for you to take your time and understand the code. Happy coding!