1. 程式人生 > >PAT乙級 檢查密碼

PAT乙級 檢查密碼

檢查密碼 (15 分)

題目描述:

本題要求你幫助某網站的使用者註冊模組寫一個密碼合法性檢查的小功能。該網站要求使用者設定的密碼必須由不少於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.

AC程式碼:

#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    int N;
    cin >> N;
    getchar();
    while(N--)
    {
        string temp;
        getline(cin,temp);
        int len = temp.length();
        if(len < 6)   //如果密碼少於6位,輸出太短了
        {
            cout << "Your password is tai duan le." << endl;
        }
        else //如果密碼長度合法
        {
            int zm = 0, sz = 0, dot = 0, qt = 0;  //分別記錄字母、數字、點和其他字元的個數
            for(int i = 0;i < len;i++)
            {
                if((temp[i]>='a'&&temp[i]<='z')||(temp[i]>='A'&&temp[i]<='Z'))  //判斷是否為字母
                {
                    zm++;   
                }
                else if(temp[i]>='0'&&temp[i]<='9')   //判斷是否為數字
                {
                    sz++;
                }
                else if(temp[i] == '.')   //判斷是否有小數點
                {
                    dot++;
                }
                else   //不是字母數字小數點就是其他字元了
                {
                    qt++;
                }
            }
            if(qt)   //若其他字元的個數不為0
            {
                cout << "Your password is tai luan le." << endl;
            }
            else if(sz==0)  //若沒有數字字元
            {
                cout << "Your password needs shu zi." << endl;
            }
            else if(zm==0)  //若沒有字母字元
            {
                cout << "Your password needs zi mu." << endl;
            }
            else   //完美
            {
                cout << "Your password is wan mei." << endl;
            } 
        }
    }    
    return 0;
}