我已经制作了一个应用程序来解决一些使用矩阵的计算,我想对用户进行身份验证,以便在程序启动时授予他们访问权限。
我会告诉你我已经做过的事情。
int main()
{
const string USERNAME = "claudiu";
const string PASSWORD = "123456";
string usr, pass;
cout << "Enter Username : ";
cin >> usr;
if(usr.length() < 4)
{
cout << "Username length must be atleast 4 characters long.";
}
else
{
cout << "Enter Password : ";
cin >> pass;
if(pass.length() < 6)
{
cout << "Password length must be atleast 6 characters long";
}
else
{
if(usr == USERNAME && pass == PASSWORD)
{
cout << "\n\nSuccessfully granted access" << endl;
}
else
{
cout << "Invalid login details" << endl;
}
}
}
这就是我的代码的样子。我想要做的就是当我输入错误的用户名或错误的密码时,程序会显示我写的信息然后让我介绍另一个用户名和密码,当我正确地介绍它们时,程序就会启动。
答案 0 :(得分:2)
我会创建一个logged_in
变量,然后在条件通过时将其设置为true
并在while循环中运行整个登录过程:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const string USERNAME = "claudiu";
const string PASSWORD = "123456";
string usr, pass;
bool logged_in = false;
while (!logged_in)
{
cout << "Enter Username : ";
cin >> usr;
if (usr.length() < 4)
{
cout << "Username length must be atleast 4 characters long.";
}
else
{
cout << "Enter Password : ";
cin >> pass;
if (pass.length() < 6)
{
cout << "Password length must be atleast 6 characters long";
}
else
{
if (usr == USERNAME && pass == PASSWORD)
{
cout << "\n\nSuccessfully granted access" << endl;
logged_in = true;
}
else
{
cout << "Invalid login details" << endl;
}
}
}
}
cout << "Passed login!\n";
}