1067 试密码
思路:
用一个string存储密码,每次用getline来获取用户输入的密码s
用整型变量cnt来记录尝试的次数
如果得到的s是#,就退出循环;
如果得到正确密码就输出正确语句退出循环;
如果得到错误密码就继续循环读取;
如果cnt==n,就输出超次语句退出循环。
坑点:
- 使用getline(cin, s)语句需要导入<string>包
- 用getline之前要先用getchar()来读取上一行直接用cin读取留下的换行符
#include<stdio.h>
#include<iostream>
#include<string>
using namespace std;
int main(void) {
string psd;
int n;
cin >> psd >> n;
int cnt = 0;
string s;
getchar(); // 读取第一行最后的换行符
getline(cin, s);
while (true) {
if (s == "#") { break; }
if (s == psd) { cout << "Welcome in"; break; }
else { cout << "Wrong password: " << s << endl; }
cnt++;
if (cnt == n) { cout << "Account locked"; break; }
getline(cin, s);
}
return 0;
}