- #include <iostream>
- #include <unistd.h>
- #include <termios.h>
- #include <errno.h>
- using namespace std;
- bool setEcho(int fd,bool option)
- {
- int err;
- struct termios term;
- if(tcgetattr(fd,&term)==-1)
- {
- cout <<"获得终端属性失败"<<endl;
- return false;
- }
- if(option)
- {
- term.c_lflag|=ECHO;
- }
- else
- {
- term.c_lflag &=~ECHO;
- }
- err=tcsetattr(fd,TCSAFLUSH,&term);
- if(err==-1 && err== EINTR)
- {
- cout <<"设置终端属性失败"<<endl;
- return false;
- }
- return true;
- }
- string inputPassword(bool repeat)
- {
- string ret;
- char buf[256];
- //关回显
- setEcho(STDIN_FILENO,false);
- while(true)
- {
- cout<<"Please input password :"<<endl;
- cin.getline(buf,256);
- buf[255]='\\0';
- ret=buf;
- if(repeat)
- {
- cout<<"Please repeat password :"<<endl;
- cin.getline(buf,256);
- buf[255]='\\0';
- if(ret==buf)break;
- else cout<<"two inputs are diffrent"<<endl;
- }
- else break;
- }
- //开回显
- setEcho(STDIN_FILENO,true);
- return ret;
- }
- int main(){
- inputPassword(true);
- }
- //该片段来自于http://www.codesnippet.cn/detail/3003201512018.html
来源: http://www.codesnippet.cn/detail/3003201512018.html