控制台程序输入密码涉及到关闭回显,只要关闭了回显,别的就是常规操作了。输入的密码要不要显式成星号或者别的,纯属个人喜好。
主要用到下面几个知识:
输完密码还要把回显打开,所以最好包装起来,这是打开或关闭回显的代码:
- bool setEcho(int fd,bool option)
- {
- int err;
- struct termios term;
-
- if(tcgetattr(fd,&term)==-1)
- {
- thelog<<"获得终端属性失败"<
- return false;
- }
-
- if(option)
- {
- term.c_lflag|=ECHO;
- }
- else
- {
- term.c_lflag &=~ECHO;
- }
- err=tcsetattr(fd,TCSAFLUSH,&term);
- if(err==-1 && err==EINTR)
- {
- thelog<<"设置终端属性失败"<
- return false;
- }
-
- return true;
- }
输入密码的代码,参数控制是否需要输入两次(一般用于设置密码):
- string inputPassword(bool repeat)
- {
- string ret;
- char buf[256];
-
- //关回显
- setEcho(STDIN_FILENO,false);
-
- while(true)
- {
- cout<<"Please input password >"<
- cin.getline(buf,256);
- buf[255]='\0';
- ret=buf;
- if(repeat)
- {
- cout<<"Please repeat password >"<
- cin.getline(buf,256);
- buf[255]='\0';
- if(ret==buf)break;
- else cout<<"two inputs are diffrent"<
- }
- else break;
- }
-
- //开回显
- setEcho(STDIN_FILENO,true);
- return ret;
- }
代码很简单。
以上代码是Unix/Linux下运行的,用到了C++,但关键关键操作完全是C的。
(这里是结束)
-
相关阅读:
数据挖掘(3)特征化
前端常见的安全问题及防范措施
Centos6 密钥登陆,解决所选的用户密钥未在远程主机上注册
C++ bool类型变量赋值true,输出结果却是false?是因为cin输入的true会被当成字符串,所以bool变量原值不变吗?
抖音矩阵系统,抖音矩阵系统源码。hei
MAC安装JDK8
基于php停车场
已解决com.netflix.client.ClientException Eureka客户端异常的正确解决方法,亲测有效!!!
视频流远程控制启动教程
大屏项目开发
-
原文地址:https://blog.csdn.net/2301_77171572/article/details/134069207