PAT Level B-Test Password

Topic description
When you try to log in to a system but forget your password, the system generally only allows you to try a limited number of times. When the number of allowed times is exceeded, the account will be locked.

This question asks you to implement this small function.

Input format
Enter a password and a positive integer N on the first line, which are the correct password and the number of attempts allowed by the system.
Each subsequent line gives a non-empty string ending with a carriage return, which is the password that the user is trying to enter.
When only a single read line #when the character input end, and this line is not the user's input.

The input is guaranteed to have at least one attempt.
The password is a non-empty string of no more than 20, no spaces, Tab, or carriage return

Output format
For each input of the user,

  • If it is the correct password and the number of attempts does not exceed N, output in one line Welcome inand end the program;
  • If it is wrong, output in the format in one line Wrong password: 用户输入的错误密码;
  • When the number of error attempts reaches N times, another line is output Account lockedand the program ends.

Input example 1
Correct%pw 3
correct%pw
Correct@PW
whatisthepassword!
Correct%pw

输出样例1
Wrong password: correct%pw
Wrong password: Correct@PW
Wrong password: whatisthepassword!
Account locked

Input sample 2
cool@gplt 3
coolman@gplt
coollady@gplt
cool@gplt
try again

Output sample 2
Wrong password: coolman@gplt
Wrong password: coollady@gplt
Welcome in

Data range
N ≤ 10


Problem solution
simulation:

细节: If the number is read when the first row, a second row with a getlineread into the string, with the first getcharfiltered off 换行, otherwise it will read a blank line;

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
    
    
	int limit;
	string password, str;
	
	cin >> password >> limit;
	getchar();                                              // 过滤换行
	
	int cnt = 0;
	while(getline(cin, str), str != "#")
	{
    
    
		if(str == password) 
		{
    
    
			cout << "Welcome in" << endl;
			break;
		}
		else
		{
    
    
			cnt ++;
			cout << "Wrong password: " << str << endl;
			if(cnt == limit)
			{
    
    
				cout << "Account locked" << endl;
				break;
			}
		}
	}
	
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46239370/article/details/114378452