1067 试密码 (20 分)
当你试图登录某个系统却忘了密码时,系统一般只会允许你尝试有限多次,当超出允许次数时,账号就会被锁死。本题就请你实现这个小功能。
输入格式:
输入在第一行给出一个密码(长度不超过 20 的、不包含空格、Tab、回车的非空字符串)和一个正整数 N(≤ 10),分别是正确的密码和系统允许尝试的次数。随后每行给出一个以回车结束的非空字符串,是用户尝试输入的密码。输入保证至少有一次尝试。当读到一行只有单个 # 字符时,输入结束,并且这一行不是用户的输入。
输出格式:
对用户的每个输入,如果是正确的密码且尝试次数不超过 N,则在一行中输出 Welcome in
,并结束程序;如果是错误的,则在一行中按格式输出 Wrong password: 用户输入的错误密码
;当错误尝试达到 N 次时,再输出一行 Account locked
,并结束程序。
输入样例 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
输入样例 2:
cool@gplt 3
coolman@gplt
coollady@gplt
cool@gplt
try again
#
输出样例 2:
Wrong password: coolman@gplt
Wrong password: coollady@gplt
Welcome in
坑1:尝试的密码可能包含空格,所以使用getline,而getline要注意,第一行输入后需要进行一次getline 或者getchar,否则会出现str为空的情况,另外最好别用sacnf读取字符串,因为还需要str.resize否则str就是空,但是用了resize就不能只能==比较了,麻烦
坑2:也就是测试点2检查的,不是 https://blog.csdn.net/id33749110/article/details/86564278里说的直接是个#和https://blog.csdn.net/qq_43749739/article/details/87875093说的第一行给出的密码和数字后面不一定紧跟换行符【测试点二答案错误】
而是在i=n时候并且密码错了输出锁死。我测试点2错的原因是 没有判断是不是i=n,而是直接看是不是有正确密码了,没有直接输出锁死
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string mima;
int n;
//scanf("%s %d",&mima[0],&n);
cin>>mima>>n;
vector<string> vec;
string str;
getchar();//或者getline(cin,str);
getline(cin,str);
while(str!="#") {
vec.push_back(str);
getline(cin,str);
}
int getin=0;
for(int i=1; i<vec.size()+1; i++) {
string str=vec[i-1];
if(str==mima&&i<=n) {
cout<<"Welcome in";
getin=1;
break;
}
else if(i<=n)
cout<<"Wrong password: "<<str<<endl;
if(i==n){
cout<<"Account locked";
break;
}
}
return 0;
}
测试点2没过的代码如下
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
string mima;
int n;
//scanf("%s %d",&mima[0],&n);
cin>>mima>>n;
vector<string> vec;
string str;
getchar();//作者getline(cin,str);
getline(cin,str);
while(str!="#") {
vec.push_back(str);
getline(cin,str);
}
int getin=0;
for(int i=1; i<vec.size()+1; i++) {
string str=vec[i-1];
if(str==mima&&i<=n) {
cout<<"Welcome in";
getin=1;
break;
}
else if(i<=n)
cout<<"Wrong password: "<<str<<endl;
}
if(getin==0&&vec.size()>0)
cout<<"Account locked";
return 0;
}