简体   繁体   中英

Error with username/password checker in C++

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM