c++中用户名/密码检查器错误

Error with username/password checker in C++

本文关键字:检查 错误 密码 用户 c++      更新时间:2023-10-16

我目前正在尝试学习一些基本的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;

修复问题