confusedstudent
confusedstudent

Reputation: 5

Where's the error? Code for password entry in C++

I'm a beginner. After the execution of this simple password code, it keeps showing invalid even after entering the correct password. Anyone out there who can help me out?

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    string username;
    int password[4]={0},i,realname[4]={1,2,4,8},j,temp=0;
    for(j=0;j<3;j++)
    {
        cout<<"\nUsername: ";
        cin>>username;
        if(username=="admin")
        {
            temp++;
        }
        cout<<"\nPassword: ";
        for (i = 0; i < 4;i++)
        {
            password[i]=getch();
            cout<<"*";
            if(password[i]==realname[i])
            {
                temp++;
            }
        }
        if(temp==5)
        {
            cout<<"Login Success!";
            break;
        }
        else
        {
            cout<<"\nInvalid username or password.";
            j=0;
        }
    }
}

Upvotes: 0

Views: 120

Answers (1)

Konjit W
Konjit W

Reputation: 226

Your code is giving you Invalid username or password it is because the value of temp is never update inside the for loop. The line if(password[i]==realname[i]) is evaluating to false because it is trying to compare the ascii representation of the user input which are¨[49, 50, 51, 52] to realname[1, 2, 4, 8] array. Either you have to convert the user input to an int or make the password and the realname char type.

#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
    string username;
    int i, j, temp=0;
    char realname[4]={'1', '2', '4', '8'};
    char password[4] = {'0'};
    for(j=0;j<3;j++)
    {
        cout<<"\nUsername: ";
        cin>>username;
        if(username=="admin"){
            temp++;
        }
        cout<<"\nPassword: ";
        for (i = 0; i < 4;i++)
        {
            password[i]=static_cast<char>(getch());
            cout<<"*";
            if(password[i]==realname[i])
            {
                temp++;
            }
        }
        std::cout<< "\n";
        if(temp == 5)
        {
            cout<<"Login Success!\n";
            break;
        }
        else
        {
            cout<<"\nInvalid username or password\n.";
            j=0;
        }
    }
}

Upvotes: 1

Related Questions