要求:
➢设置一个密码,允许数字和字母组合。
➢如果输入字符低于某个数值(比如6或8),提示:密码过短请重试。
➢连续输入3次错误密码,不再允许输入密码。
➢可以选择密码重置,将之前的密码覆盖。
实现:
1.设置密码
void SetPassword(char * x) //此函数用于设置密码
{
cout << "Please set your password:" << endl;
cin.getline(x, MAX); //从键盘输入不超过MAX位的字符作为密码
if (strlen(x) < MIN) //判断输入密码长度,MIN为题目要求的密码最短位数
{
cout << "The password is too short.";
SetPassword(x); //若密码输入过短,会再次要求输入
}
else
cout << "The password is set successfully." << endl;
cout << "------------------------------" << endl;
}
2.输入密码
void Decipher(char*y) //此函数用于解开密码
{
int i;
char str[MAX];
cout << "Please enter a password:" << endl;
for (i = 0; i < 3; i++) {
cin.getline(str, MAX); //从键盘输入一串字符
if (strcmp(y, str) == 0) { //判断输入字符串和密码是否相同
cout << "Deciphering successfully!" << endl;
break;
}
else {
cout << "Please enter your password again and you have "
<<2-i <<" more chance." << endl;
}
}
cout << "------------------------------" << endl;
}
3.main函数部分
int main()
{
int a = 0;
char code[MAX];
char* p1 = code;
SetPassword( p1 );
while (a != 3) {
cout << "Please choose what you want to do next:" << endl
<< "1.Reset the password\t2.Unlock the password\t3.Come to an end" << endl;
//1.重置密码 2.输入密码 3.结束程序
cin >> a;
getchar(); //把\n“吸”掉(可以去掉此行,运行程序,来进行对比)
if (a == 1) {
SetPassword(p1);
}
else if (a == 2) {
Decipher( p1 );
}
}
}
4.总程序
#include <iostream>
#include <string>
#define MIN 6 //限定密码最小长度
#define MAX 100
using namespace std;
void SetPassword(char * x)
{
cout << "Please set your password:" << endl;
cin.getline(x, MAX);
if (strlen(x) < MIN)
{
cout << "The password is too short.";
SetPassword(x);
}
else
cout << "The password is set successfully." << endl;
cout << "------------------------------" << endl;
}
void Decipher(char*y)
{
int i;
char str[MAX];
cout << "Please enter a password:" << endl;
for (i = 0; i < 3; i++) {
cin.getline(str, MAX);
if (strcmp(y, str) == 0) {
cout << "Deciphering successfully!" << endl;
break;
}
else {
cout << "Please enter your password again and you have "
<<2-i <<" more chance." << endl;
}
}
cout << "------------------------------" << endl;
}
int main()
{
int a = 0;
char code[MAX];
char* p1 = code;
SetPassword( p1 );
while (a != 3) {
cout << "Please choose what you want to do next:" << endl
<< "1.Reset the password\t2.Unlock the password\t3.Come to an end" << endl;
cin >> a;
getchar();
if (a == 1) {
SetPassword(p1);
}
else if (a == 2) {
Decipher( p1 );
}
}
}
运行结果:
问题提出:
有大佬知道为什么这里会出现两条线吗?QAQ
这学期刚学C++ ,感觉头好痒,要长脑子了ᕦ༼༎ຶ_༎ຶ༽ᕗ