C++ 如何使Do功能仅重复密码输入

C++ 如何使Do功能仅重复密码输入,c++,visual-c++,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() { //Userna

我终于找到了如何实现我想要的功能,但是我遇到的问题是,我只想让它重复要求输入密码,而不是用户名和密码

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

然后将输入项放在passworddo循环之外并检查用户名

如果您希望允许用户重新输入太短的用户名,则可以将这些用户名放在另一个do循环中。没有规定只允许一个循环:

类似伪代码的东西

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

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

关于你是否告诉用户为什么他们的数据无效,有一个哲学上的争论。我不想被牵扯进去,保安人员可以得到一点。。。强烈。

do之后{}括号内的所有内容都将循环,因此请取出不希望循环的内容。或者,在另一个do循环中接受密码。