PAT B1081 检查密码(C++)

PAT甲级目录 | PAT乙级目录

题目描述

B1081 检查密码

解题思路

字符串处理,可以用 ctype 头文件中的函数。

易错点

  • 当密码太短不考虑是否合法

也许陌生的知识点

  • s.erase(ans.begin());
    • 删除字符串第一个字符
    • 所需头文件: string
  • s.empty()

    • 判断一个字符串是否为空字符串
    • 所需头文件: string
  • ctype 头文件中包含的一系列处理单个字符的函数:

    • isalnum()
      • 判断字符是否为字母或者数字
    • isalpha()
      • 判断字符是否为字母
    • isblank()
      • 判断字符是否为空格
    • isdigit()
      • 判断字符是否为数字
    • islower()
      • 判断字符是否为小写字母
    • isupper()
      • 判断字符是否为大写字母
    • y = tolower(x)
      • 将大写字母转换为小写字母
    • y = toupper(x)
      • 将小写字母转换为大写字母

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <cstdio>
#include <cctype>
#include <iostream>
#include <string>
using namespace std;
int main(){
int N;
string str;
scanf("%d\n", &N);
for(int i = 0; i < N; i++){
int len = 0, hasdigit = 0, hasalpha = 0, valid = 1;
getline(cin, str);
if(str.length() < 6) cout << "Your password is tai duan le." << endl;
else {
while(!str.empty() && valid){
if(!isalnum(str[0]) && str[0] != '.') valid = 0;
if(isdigit(str[0])) hasdigit = 1;
if(isalpha(str[0])) hasalpha = 1;
str.erase(str.begin());
}
if(!valid) cout << "Your password is tai luan le." << endl;
else if(hasalpha == 1 && hasdigit == 0) cout << "Your password needs shu zi." << endl;
else if(hasalpha == 0 && hasdigit == 1) cout << "Your password needs zi mu." << endl;
else cout << "Your password is wan mei." << endl;
}
}
return 0;
}