1. 程式人生 > >PAT乙級1081 檢查密碼(15 分)

PAT乙級1081 檢查密碼(15 分)

1081 檢查密碼(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.
#include <iostream>
#include <ctype.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	getchar();
	for(int i=0;i<n;i++)
	{
		string s;
		getline(cin,s);
		if(s.length()<6)
		printf("Your password is tai duan le.\n");
		else
		{
			int isluan=0,hasnum=0,hasalphabet=0;
			for(int j=0;j<s.length();j++)
			{
				if(s[j]!='.'&&!isalnum(s[j]))
				isluan=1;
				else if(isalpha(s[j]))
				hasalphabet=1;
				else if(isdigit(s[j]))
				hasnum=1;
			}
			if(isluan==1)
			cout << "Your password is tai luan le.\n";
			else if(hasnum==0)
			cout << "Your password needs shu zi.\n";
			else if(hasalphabet==0)
			cout << "Your password needs zi mu.\n";
			else
			cout << "Your password is wan mei.\n";
		}
	}
} 

解析: getchar()是為了接收 輸入n後的空格或是回車 以免這些元素誤入字串中造成判定失敗

因為輸入的字串可能有空格 所以不能用cin 採用getline()

匯入<ctype.h>庫 利用函式