Error with username/password checker in C++

2k views Asked by At

I am currently attempting to learn some basic C++ programming and decided to make myself a basic 3 attempt username and password checker to practice some of what I have read up on. Problem is when I run the program and enter an incorrect username and password first, the program will no longer recognize the correct username and password if entered on the second or third attempt. I have been looking at this for quite some time now and can't seem to get it to work. I have even included a currently commented out line to make sure that the program is reading the proper inputs, which it is.

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int attempts=0;
    string username, password;
    while (attempts < 3)
    {
        cout<<"\nPlease enter your username and password seperated by a space.\n";
        getline( cin, username, ' ');
        cin>>password;
        if (username == "Ryan" && password == "pass")
        {
            cout<<"\nYou have been granted access.";
            return 0;
            cin.get();
        }
        else
        {
            attempts++;
            //cout<<username <<" " <<password << "\n";
            cout<<"Incorrect username or password, try again.";
            cout<<"\nAttempts remaining: "<<3-attempts <<"\n";
        }
    }
    cout<<"\nOut of attempts, access denied.";
    cin.get();

}

Any help or critique is greatly appreciated.

1

There are 1 answers

3
RedAgito On BEST ANSWER

Your username includes a newline character '\n' after the first attempt due to getline

Changing your cin usage from

getline( cin, username, ' ');
cin>>password;

to

cin >> username;
cin >> password;

fixes your problem