目录
一,目标功能
·能匹配原先设置好的用户名和密码进行验证
·输入密码时需要实时更新显示
·密码输入过多或输错可回删
·输入错误次数过多限制登录验证
二,实现代码
\r 换行
\b 相当于Backspace
#include <iostream>
#include <conio.h>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
char name[20];
name[0] = '\0';
char password[20];
password[0] = '\0';
int i = 0;
char ch;
ch = '\0';
int times=5;//最多尝试五次
while (times)
{
times--;
if(!times)
{
cout<<"尝试次数过多,请稍后再试\n";//如有需要,可利用时间写程序。
break;
}
i=0;//注意每次重新输入i要更新为0,否则password数组存储内容包括前面错误的密码输入
cout << "输入用户名:";
cin >> name;
cout << "输入密码:";
while(1)
{
ch = _getch();
if (ch == '\r') break;
if (ch == '\b') { cout << "\b"; i--; } //这里cout一个\b(backsapce)即可
else { password[i++] = ch; cout << "*"; }
}
cout << endl;
password[i] = '\0';
// cout<<password<<endl;
if (strcmp(name, "admin") == 0 && strcmp(password, "123") == 0)
{
cout << "登录成功!" << endl;//符合则直接显示成功,不必退出再显示,减少麻烦和程序可读性
break;
}
system("cls");
cout << "密码或用户名错误,请重新输入:";
}
return 0;
}