简单的密码验证

Simple password verification

本文关键字:验证 密码 简单      更新时间:2023-10-16

我对编码相对较新,可以帮助为此代码添加一个简单的密码>验证。应提示用户输入密码>一旦他们选择选项 4,如果密码错误,他们可以重试或返回>到开始,如果密码正确,他们继续选项 4

int bball::menu()
int menuChoice;
string passWord;
cout << "n1. Print out all player statistics (Enter 1)" << endl;
cout << "2. Print out specific player's stats (Enter 2)" << endl;
cout << "3. Print specific teams stats (Enter 3)" << endl;
cout << "4. Update players data (Enter 4)" << endl;
cout << "5. Close menu (Enter 5)" << endl;
cout << "> ";
cin >> menuChoice;
while (menuChoice < 1 || menuChoice > 5 ) {
cout << "Invalid choice";
cout << "> ";
cin >> menuChoice;
}
while (menuChoice = 5)
{
cout << "Enter password: ";
cin >> passWord;
if (passWord == "Yaboi321")
return menuChoice;
else
cout << "Wrong Password";
}
/*if (menuChoice = 5)
{
cout << "Enter password: ";
cin >> passWord;
if (passWord == "Yaboi321")
return menuChoice;
else
cout << "Wrong Password";
}
*/
return menuChoice;

}

您与 5 进行比较(假设 = 在第二个时间中更正为 ==),但在问题中它是关于选项 4 的

您不管理与数字不同的输入,在这种情况下您将最终循环,在 EOF 情况下,菜单选项和密码都相同

提案 :

#include <string>
#include <iostream>
using namespace std;
int menu()
{
cout << "n1. Print out all player statistics (Enter 1)" << endl;
cout << "2. Print out specific player's stats (Enter 2)" << endl;
cout << "3. Print specific teams stats (Enter 3)" << endl;
cout << "4. Update players data (Enter 4)" << endl;
cout << "5. Close menu (Enter 5)" << endl;
int menuChoice;
for (;;) {
cout << "> ";
if (!(cin >> menuChoice)) {
// not a number, clear error then bypass word
cin.clear();
string dummy;
if (!(cin >> dummy))
// EOF
return -1; // indicate an error
menuChoice = -1;
}
if ((menuChoice < 1) || (menuChoice > 5))
cout << "Invalid choice" << endl;
else
break;
}
if (menuChoice == 4) {
string password;
do {
cout << "Enter password: ";
if (!(cin >> password))
// EOF
return -1; // indicate an error
} while (password != "Yaboi321");
}
return menuChoice;
}

编译和执行:

pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra m.cpp
pi@raspberrypi:/tmp $ ./a.out
1. Print out all player statistics (Enter 1)
2. Print out specific player's stats (Enter 2)
3. Print specific teams stats (Enter 3)
4. Update players data (Enter 4)
5. Close menu (Enter 5)
> 1
choice : 1
pi@raspberrypi:/tmp $ ./a.out
1. Print out all player statistics (Enter 1)
2. Print out specific player's stats (Enter 2)
3. Print specific teams stats (Enter 3)
4. Update players data (Enter 4)
5. Close menu (Enter 5)
> a
Invalid choice
> 0
Invalid choice
> 4
Enter password: aze
Enter password: Yaboi321
choice : 4

在给定数量的连续无效密码读取后停止询问密码并返回 1..5 中的数字以表示情况可能会很有趣,否则无法停止需要密码的循环