Claudiu Carabulea
Claudiu Carabulea

Reputation: 13

Password to a program

I've made an app that solves some computations with matrices, and I want to authenticate users in order to grant them access when the program starts.

I will show you what I've done already.

int main() 
{

const string USERNAME = "claudiu";
const string PASSWORD = "123456";
string usr, pass;

cout << "Enter Username : ";
cin >> usr;

if(usr.length() < 4)
{
    cout << "Username length must be atleast 4 characters long.";
}
else 
{
    cout << "Enter Password : ";
    cin >> pass;
    if(pass.length() < 6)
    {
        cout << "Password length must be atleast 6 characters long";

    }
    else 
    {
        if(usr == USERNAME && pass == PASSWORD)
        {
            cout << "\n\nSuccessfully granted access" << endl;
        }
        else
        {
            cout << "Invalid login details" << endl;

        }
    }
}

This is how my code looks like. All I want to do is that when I enter a wrong username or a wrong password the program shows the message I wrote and then let me introduce another username and password and when I introduce them correctly, the program starts.

Upvotes: 1

Views: 996

Answers (1)

Ben
Ben

Reputation: 6348

I would make a logged_in variable, then set it to true when the condition is passed and run the whole login process in a while loop:

#include <iostream>
#include <string>

using namespace std;

int main()
{

    const string USERNAME = "claudiu";
    const string PASSWORD = "123456";
    string usr, pass;
    bool logged_in = false;
    while (!logged_in)
    {
        cout << "Enter Username : ";
        cin >> usr;

        if (usr.length() < 4)
        {
            cout << "Username length must be atleast 4 characters long.";
        }
        else
        {
            cout << "Enter Password : ";
            cin >> pass;
            if (pass.length() < 6)
            {
                cout << "Password length must be atleast 6 characters long";

            }
            else
            {
                if (usr == USERNAME && pass == PASSWORD)
                {
                    cout << "\n\nSuccessfully granted access" << endl;
                    logged_in = true;
                }
                else
                {
                    cout << "Invalid login details" << endl;

                }
            }
        }
    }
    cout << "Passed login!\n";
}

Upvotes: 2

Related Questions