密码尝试限制

时间:2015-10-05 20:53:30

标签: c++ loops

这是一个c ++新手。

如何限制在此程序中尝试输入密码的次数?到目前为止,它会重新打印,直到输入正确的密码。我想设置3次尝试的限制,并执行“达到的尝试限制”'或类似的东西。

{

string password;

while (true)
{
    cout << "Please enter your password.\n";
    cin >> password;
    if (password == "password")
    {
        cout << "Welcome!\n";
        break;
    }
   cout << "Please try again.\n";
   }
}

提前致谢,

尔杰斯。

1 个答案:

答案 0 :(得分:1)

您可以使用for循环:

string password;

//Ask for a password as long as the user hasn't incorrectly entered one three or more times
for (int tries = 0; tries < 3; ++tries)
{
    cout << "Please enter your password.\n";
    cin >> password;
    if (password == "password")
    {
        cout << "Welcome!\n";
        break;
    }
    cout << "Please try again.\n";
}

//If the password limit was reached without a correct password, send them an error message
if (password != "password") cout << "Sorry, try again later.\n";