简单的密码验证

时间:2019-04-18 21:21:13

标签: c++

  

对于编码来说相对较新,可以使用帮助添加此代码的简单密码验证。应该提示用户输入密码,然后选择选项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;

}

1 个答案:

答案 0 :(得分:0)

您与5进行比较(假设=在第二个 while 中被更正为==),但问题是关于选项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以外的数字以表示情况,否则无法停止需要密码的循环< / p>