如何使Do功能只重复输入密码

时间:2015-02-13 07:25:00

标签: c++ visual-c++

我终于想出了如何制作我正在寻找的功能,但是我遇到的问题是我想让它只重复询问密码输入,而不是用户名和密码。

#include "stdafx.h"
#include <iostream> // library that contains basic input output functions
#include <string> // library for c++ strings

using namespace std;

int main()
{
    //Username and Password to validate credentials
    const string USERNAME = "myself";
    const string PASSWORD = "stanley";
    const string USERNAME2 = "otherperson";
    const string PASSWORD2 = "otherpassword";
    //strings in which user will enter username and password 
    string username, password;
    int passattempts = 0;
    do{
    // Prompting user to input username
    cout << "Enter Username : ";
    cin >> username;

    //Checking if username length is less than 4 characters then display an error message
    if (username.length() < 4)
    {
        cout << "Username length must be atleast 4 characters long.";
    }
    else  //if username length is greater than 3
    {
        //promprting user for password
        cout << "Enter Password : ";
        cin >> password;
        //Checking if password length is less than 6 characters then display an error message
        if (password.length() < 6)
        {
            cout << "Password length must be atleast 6 characters long.";
        }
        else //if password length is greater than 5

        {
            //Checking if user's entered credentials are equal to actual USERNAME and PASSWORD 
            if (username == USERNAME && password == PASSWORD || username == USERNAME2 && password == PASSWORD2)
            {
                cout << "User credentials are correct!!!" << endl;
                break;
            }
            else
            {
                cout << "Invalid login details" << endl;
                ++passattempts;
            }
        }
    }
    } while (passattempts != 3);
    system("pause");
    return (0);
}

1 个答案:

答案 0 :(得分:2)

然后在密码do循环之外输入(并检查)用户名。

如果您希望允许用户重新输入太短的用户名,您可以随时将这些内容置于另一个do循环中。没有规则说你只允许一个循环:)

类似(伪代码)

do
{
   prompt for username
   read username
} while (username invalid)

do
{
   prompt for password
   read password
} while (password invalid)

关于你是否告诉用户为什么他们的数据无效,还有一个哲学论点。我没有被吸引,安全人员可以得到一点...... 激烈