本题要求你帮助某网站的用户注册模块写一个密码合法性检查的小功能。该网站要求用户设置的密码必须由不少于6个字符组成,并且只能有英文字母、数字和小数点 .,还必须既有字母也有数字。
输入格式:
输入第一行给出一个正整数 N(≤ 100),随后 N 行,每行给出一个用户设置的密码,为不超过 80 个字符的非空字符串,以回车结束。
输出格式:
对每个用户的密码,在一行中输出系统反馈信息,分以下5种:
①如果密码合法,输出Your password is wan mei.;
②如果密码太短,不论合法与否,都输出Your password is tai duan le.;
③ 如果密码长度合法,但存在不合法字符,则输出Your password is tai luan le.;
④如果密码长度合法,但只有字母没有数字,则输出Your password needs shu zi.;
⑤如果密码长度合法,但只有数字没有字母,则输出Your password needs zi mu.。
输入样例:
5
123s
zheshi.wodepw
1234.5678
WanMei23333
pass*word.6
输出样例:
Your password is tai duan le.
Your password needs shu zi.
Your password needs zi mu.
Your password is wan mei.
Your password is tai luan le.
思路:
①判断长度是否合法,小于指定长度直接判定不合法
②遍历密码字符串。判断是否含有除字母,数字,小数点之外的字符
③判断密码中是否同时有字符和数字的字符
测试案例都很正常,知识需要考虑密码中含有空格的问题,测试点二的案例就是含有空格
代码:
#include<iostream>
#include<string>
#include<cctype>
using namespace std;
//判断长度是否合法,小于指定长度直接判定不合法
//遍历密码字符串。判断是否含有除字母,数字,小数点之外的字符
//判断密码中是否同时有字符和数字的字符
bool haveNum(string s)//判断是否有数字
{
bool flag = false;
for (int i = 0; i < s.length(); i++)
{
if (isdigit(s[i]))
{
flag = true;
break;
}
}
return flag;
}
bool haveLetter(string s)//判断是否有字母
{
bool flag = false;
for (int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
flag = true;
break;
}
}
return flag;
}
bool isLegal(string s)//判断密码是否合法
{
bool flag = true;
for (int i = 0; i < s.length(); i++)
{
if (!(isalnum(s[i]) || s[i] == '.'))
{
flag = false;
break;
}
}
return flag;
}
int main()
{
int N;
string s;
cin >> N;
cin.get();//cin是丢弃回车的,cin.get()是保留回车的,防止下面getline读到回车
for (int i = 0; i < N; i++)
{
getline(cin, s);//防止密码中有空格,测试点二密码中有空格
if (s.length()<6)//长度不合法
{
cout << "Your password is tai duan le." << endl;
continue;
}
else//长度合法
{
if (!isLegal(s))//密码不合法
{
cout << "Your password is tai luan le." << endl;
continue;
}
else//密码合法
{
if (!haveNum(s))
{
cout << "Your password needs shu zi." << endl;
continue;
}
if (!haveLetter(s))
{
cout << "Your password needs zi mu." << endl;
continue;
}
if (haveNum(s) || haveLetter(s))
{
cout << "Your password is wan mei." << endl;
continue;
}
}
}
}
return 0;
}