c++ - C++ 中的用户名/密码检查器出错

标签 c++ password-checker

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

解决你的问题

关于c++ - C++ 中的用户名/密码检查器出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30420752/

相关文章:

c++ - cmake:我必须按什么顺序指定 TARGET_LINK_LIBRARIES

c++ - dll加载时出错

c++ - CArray 的析构函数大约需要 30 秒才能运行

c++ - Win32 程序在调用 GetSaveFileName() 或 SHBrowseForFolder() 时在 Windows 8 上崩溃

java - 带有自定义异常 Java 的密码检查器无输出

复杂密码的 Javascript 验证

javascript - 密码强度计

Java 密码模式

c++ - 如何正确使用互斥锁?