C++ 如何在终端处于原始模式时多次尝试输入密码?
我正在用C创建一个登录菜单++ 我希望在程序终止之前,给用户3次输入密码的尝试 如果用户第一次获得正确的密码,我的代码运行良好。然后它会进入主菜单。但是,如果用户密码错误。终端将运行至:C++ 如何在终端处于原始模式时多次尝试输入密码?,c++,passwords,mode,C++,Passwords,Mode,我正在用C创建一个登录菜单++ 我希望在程序终止之前,给用户3次输入密码的尝试 如果用户第一次获得正确的密码,我的代码运行良好。然后它会进入主菜单。但是,如果用户密码错误。终端将运行至: Login: Fred Password: *** Wrong password Please re-enter password: 在此之后,无论用户键入什么,都不会显示任何内容。即使ctrl-C也不能退出程序。我想知道是否有人知道发生了什么,能为我指出正确的方向 下面是在名为HomePage的类中登录方
Login: Fred
Password: ***
Wrong password
Please re-enter password:
在此之后,无论用户键入什么,都不会显示任何内容。即使ctrl-C也不能退出程序。我想知道是否有人知道发生了什么,能为我指出正确的方向
下面是在名为HomePage的类中登录方法的部分代码:
提前谢谢
如果您认为问题可能在其他地方,请告诉我,我会发布代码。我不知道您的具体问题是什么。但是,您可以应用标准调试技术来找出是哪个部分导致了问题 首先,您正在使用cfmakeraw、tcsetattr等终端执行一些奇怪的操作。听起来这可能与问题有关。因此,请删除隐藏用户输入的代码,并确保在密码正常回显到屏幕时程序正常工作。你应该能够轻松地做到这一点 完成此操作后,您可以决定您的问题是否与以下方面有关: 删除的端子属性代码,或 保留的密码循环。
这通常被称为分治调试技术。如果你删除了你认为是问题所在的代码,那么问题是否仍然存在可以帮助你决定它是否与你删除的代码有关。我刚刚在大一第一学期的最后一个项目中使用了类似的代码集。事实证明,问题来自密码屏蔽本身。 现在,我已经删除了这些部分,该程序现在工作良好,除了引脚被暴露
cout<<"Password: ";
while (loginAttempt < 3){ //The user gets to attempt to type
//the password 3 times
password = receivePassword(); //Receives password from user
if (flatMemberList[match].getPassword()==password){ //Check if the password is correct
cout<<endl<<"Welcome back "<<loginName<< endl; //If correct, display welcome message
return;
}
else{
loginAttempt++; //Record down one failed attempt
cout<<endl<<"Wrong password"<<endl; //If incorrect, display error
cout<<"Please re-enter password: ";
}
}
cout<<"you have exceeded the legal login attempts"<<endl;
exit(1);
//This method is called when the user types in a password
//The terminal's setting is first changed to 'raw' configuration
//The password are taken in one letter at a time
//It outputs to terminal "*" instead of echoing the input
string HomePage::receivePassword(){
termios oldt, newt; //The structs for manipulation
char password[PaswordLength]; //Password held here
int j = 0; //Password index
tcgetattr(STDIN_FILENO, &oldt); //Get configuration details
newt = oldt;
cfmakeraw(&newt); //Set up new 'raw' configuration structure
//Set up new terminal configuration
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
cin.ignore(1000, '\n'); //flush all the buffers
while(true){
password[j] = cin.get();
if( password[j] == '\r' ) { //check if 'enter' key is entered
password[j] = '\0'; //replace cr with null to make C string
break;
}
cout.put('*'); //echo the asterisk
j++;
} ;
//Reset terminal to old configuration
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return password;
}