怡康医药网站建设方案,优秀设计师网站,域名备案信息查询官网,妻子2018高清免费视频在C编程中#xff0c;在执行一些操作的时候#xff0c;终端需要接收用户名和密码#xff0c;那么在终端输入密码的时候#xff0c;如何不让别人看见自己的密码#xff0c;是一个较为关注的问题#xff1b;
1、问题分析
定义一个登录函数Login
//用户登录主循环bool Lo…在C编程中在执行一些操作的时候终端需要接收用户名和密码那么在终端输入密码的时候如何不让别人看见自己的密码是一个较为关注的问题
1、问题分析
定义一个登录函数Login
//用户登录主循环bool Login();int MaxLoginTimes10;
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环境下 导入包#includeconio.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下就没有#includeconio.h也就没有这个_getch()函数的定义了那么我们可以用#includetermio.h 使用tcgetattr与tcsetattr函数控制终端
定义
#ifdef _WIN32
#includeconio.h //但是linux里面没有
#else
#includetermio.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 setif (tcsetattr(fd, TCSANOW, new_tm)0){return -1;}char c getchar();//又改回去 改到旧的模式old_tmif (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)
3、测试
3.1、WIndows测试 3.2、Linux测试 完结花花