![](/img/trans.png)
[英]How to run a command as root with C or C++ with no pam in linux with password authentication
[英]Password Authentication c++
嗨,这是我第一次使用类,对我的解释不佳表示歉意。 基本上,我正在为电梯程序设置密码功能。 LogIn是我的课程的名称,其中包含字符串“ john”(这是密码)。 除了尝试输入错误密码的循环外,其他一切似乎都正常运行。
如果第一次尝试输入密码正确,则代码工作正常,但是,如果输入密码错误,则接下来的两次尝试均会出现"Incorrect name. Try again"
行,而不管密码输入是否正确。 我希望有人可以看到我要去哪里。 name
是存储的密码, nameAttempt
是用户输入的尝试输入的密码。
#include "stdafx.h"
#include "LogIn.h"
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
bool password() {
string name;
string nameAttempt;
int attempts = 0;
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2)
{
return false;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
}
}
int main()
{
bool password();
bool loggedin = password();
if(loggedin) {
cout << "Password Correct" << endl;
}
if(!loggedin) {
cout << "Incorrect Password" << endl;
cout << "Program will now terminate" << endl;
system("pause");
return 0;
}
cout << "you are now free to enter lift" << endl;
system("pause");
return 0;
}
在重试循环中,您仍然需要验证尝试输入的名称,如果名称被接受,则中断循环。
您初始化局部函数变量
int attempts = 0;
因此,while循环中的退出条件将第三次触发代码
if (attempts++ ==2)
运行,因此您将打印两次:
while (Authenticate.getName() != Authenticate.getNameAttempt())
{
if (attempts++ ==2) // increment attempts
{
return false;
}
它看起来像是故意在第二次打印后退出的,所以您的困惑很难理解。 使用调试器,这种错误很容易调查。
我认为代码应该是这样的:
while (1)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
else
{
if (attempts++ == 2)
{
return false;
}
cout << "Incorrect name. Try again" << endl;
cout << "" << endl;
cout << "Enter Name:" << endl;
cin >> nameAttempt;
Authenticate.setNameAttempt(nameAttempt);
}
}
尝试一下,甜美又简单:
cout << "nameAttempt: " << endl;
cin >> nameAttempt;
LogIn Authenticate(name, nameAttempt);
attempts = 0;
while (attempts<2)
{
if (Authenticate.getName() == Authenticate.getNameAttempt())
{
return true;
}
cout<<"Incorrect name. Try again"<< endl;
cout<< "" << endl;
cout << "Enter Name:"<< endl;
cin >>nameAttempt;
attempts++;
LogIn Authenticate(name, nameAttempt);
}
return false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.