在C++编程中,在执行一些操作的时候,终端需要接收用户名和密码,那么在终端输入密码的时候,如何不让别人看见自己的密码,是一个较为关注的问题;
1、问题分析
定义一个登录函数Login
//用户登录主循环
bool Login();
int MaxLoginTimes=10;
bool XClient::Login()
{
bool isLogin = false;
for (int i = 0;i < MaxLoginTimes;i++)
{
string username = "";
//接收用户输入
cout << "\ninput username:" << flush;
cin >> username;
//接收密码输入
string password;
cout << "input password:" << flush;
//做一个成员将密码不被别人看到
cin >> password; //在这里密码是可以被别人看见的
}
return isLogin;
}
在这种情况下,输入密码的时候,密码是会被看见的,这样很不安全
2、问题解决:
2.1、Windows环境下: 导入包#include<conio.h>
首先,定义一个专门的输入密码的成员
std::string InputPasswod();
直接使用_getch()函数,如果获取输入的字符不显示 ,是因为使用了 getch(),这个内置函数不安全过时了,用_getch()就可以解决问题了
std::string XClient::InputPasswod()
{
string password = "";
cin.ignore(4096, '\n');
for (;;)
{
//获取输入的字符不显示 getch();不安全过时了,用_getch()
char a = _getch();
if (a <= 0 || a == '\n' || a == '\r')
break;
cout << "*" << flush;
password += a;
}
return password;
}
在Login函数里面调用
bool XClient::Login()
{
bool isLogin = false;
for (int i = 0;i < MaxLoginTimes;i++)
{
string username = "";
//接收用户输入
cout << "\ninput username:" << flush;
cin >> username;
//cout << "["<< username << "]" << endl;
//接收密码输入
string password;
cout << "input password:" << flush;
//做一个成员将密码不被别人看到
password = InputPasswod();
//下面这行代码,可以查看输入的密码
cout << "[" << password <<"]" << endl;
}
return isLogin;
}
2.2、那么在Linux下就没有#include<conio.h>也就没有这个_getch()函数的定义了,那么我们可以用#include<termio.h> 使用tcgetattr与tcsetattr函数控制终端
定义:
#ifdef _WIN32
#include<conio.h> //但是linux里面没有
#else
#include<termio.h>
char _getch() //在linux自己定义一个这样的函数
{
//new_tm新的显示模式,tm_old旧的显示模式
termios new_tm;
termios old_tm;
//将原来的模式存储下来,放在结构体里面
int fd = 0;
//tcgetattr获取
if (tcgetattr(fd, &old_tm) < 0)
return -1;
//更改为原始模式,没有回显
cfmakeraw(&new_tm);
//tcsetattr set
if (tcsetattr(fd, TCSANOW, &new_tm)<0)
{
return -1;
}
char c = getchar();
//又改回去 改到旧的模式old_tm
if (tcsetattr(fd, TCSANOW, &old_tm) < 0)
{
return -1;
}
return c;
}
#endif // _WIN32
2.3、分析一些linux的tcgetattr函数和tcsetattr函数
tcgetattr用于获取终端的相关参数,而tcsetattr函数用于设置终端参数
定义一个termios结构体
termios new_tm;
termios old_tm;
将文件描述符的属性放入该结构体
tcgetattr(fd, &old_tm)
将结构体写回文件描述符,激活配置
tcsetattr(fd, TCSANOW, &new_tm)
tcsetattr(fd, TCSANOW, &old_tm)