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

How to make Do function only repeat password input

本文关键字:输入 密码 何使 Do 功能      更新时间:2023-10-16

我终于找到了如何制作我想要的函数,但我遇到的问题是,我希望它只重复要求输入密码,而不是同时要求输入用户名和密码。

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

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

如果你想让用户重新输入一个太短的用户名,你总是可以把它们放在另一个do循环中。没有规则规定你只允许一个循环:)

类似(伪代码)

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

关于是否告诉用户为什么他们的数据无效,有一个哲学上的争论。我没有被卷入其中,安保人员可以得到一点 强烈