PAT Basic 1067. 试密码

发布时间 2023-04-03 19:14:42作者: 十豆加日月

PAT Basic 1067. 试密码

1. 题目描述:

当你试图登录某个系统却忘了密码时,系统一般只会允许你尝试有限多次,当超出允许次数时,账号就会被锁死。本题就请你实现这个小功能。

2. 输入格式:

输入在第一行给出一个密码(长度不超过 20 的、不包含空格、Tab、回车的非空字符串)和一个正整数 N(≤ 10),分别是正确的密码和系统允许尝试的次数。随后每行给出一个以回车结束的非空字符串,是用户尝试输入的密码。输入保证至少有一次尝试。当读到一行只有单个 # 字符时,输入结束,并且这一行不是用户的输入。

3. 输出格式:

对用户的每个输入,如果是正确的密码且尝试次数不超过 N,则在一行中输出 Welcome in,并结束程序;如果是错误的,则在一行中按格式输出 Wrong password: 用户输入的错误密码;当错误尝试达到 N 次时,再输出一行 Account locked,并结束程序。

4. 输入样例:

Correct%pw 3
correct%pw
Correct@PW
whatisthepassword!
Correct%pw
#
cool@gplt 3
coolman@gplt
coollady@gplt
cool@gplt
try again
#

5. 输出样例:

Wrong password: correct%pw
Wrong password: Correct@PW
Wrong password: whatisthepassword!
Account locked
Wrong password: coolman@gplt
Wrong password: coollady@gplt
Welcome in

6. 性能要求:

Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB

思路:

除草题,用户输入正确的密码或是输入“#”或是达到允许尝试次数时程序结束。

有几个点需要注意。首先是用户的密码只保证以回车结束,可能含有空白字符,所以不能使用scanf()读入,需要用fgets()读入。然后就是需要用getchar()消耗掉允许尝试次数后面的换行符'\n',以使得第一个用户输入正常读入。还有就是fgets()会把换行符也读入,所以这里需要额外把换行符替换为空字符'\0',以方便strcmp()正常比较。题目没有说明用户输入的字符串长度上限,这里我直接取了一个较大的数100。

My Code:

#include <stdio.h>
#include <string.h> // strcmp header

int main(void)
{
    char correctPass[21] = "";
    int maxTry = 0;
    char userInput[100] = "";
    int i=0; // iterator
    int correctFlag = 0;
    
    scanf("%s%d", correctPass, &maxTry);
    getchar(); // consume '\n' to get correct input
    
    for(i=0; i<maxTry; ++i)
    {
        //fgets(char * s, int size, FILE * stream);
        fgets(userInput, 100, stdin);
        userInput[strlen(userInput)-1] = '\0'; // must delete '\n' for strcmp
        
        if(!strcmp(userInput, "#")) // input over
        {
            break;
        }
        else if(!strcmp(userInput, correctPass)) // correct password
        {
            correctFlag = 1;
            printf("Welcome in\n");
            break;
        }
        else // wrong password
        {
            //printf("Wrong password: %s", userInput); // can't add '\n' because fgets() will input a '\n'.
            printf("Wrong password: %s\n", userInput);
        }
    }
    if(i==maxTry && !correctFlag)
    {
        printf("Account locked\n");
    }
    
    
    return 0;
}