C++ 中的 username/password 检查器出错

Error with username/password checker in C++

我目前正在尝试学习一些基本的 C++ 编程,并决定让自己成为一个基本的 3 次尝试用户名和密码检查器来练习我所阅读的一些内容。问题是当我 运行 程序并首先输入错误的用户名和密码时,如果在第二次或第三次尝试输入时,程序将不再识别正确的用户名和密码。我已经研究了很长一段时间了,但似乎无法让它发挥作用。 我什至包括了一个当前注释掉的行,以确保程序正在读取正确的输入,确实如此。

#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();

}

非常感谢任何帮助或批评。

由于 getline

,您的用户名在第一次尝试后包含换行符“\n”

更改您的 cin 用法
getline( cin, username, ' ');
cin>>password;

cin >> username;
cin >> password;

解决了您的问题