我在Linux下做c项目时,需要登录系统,因此我就做了一个登录模块。输入密码显示*,而且可以退格删密码,所以分享给大家以供参考。注:不用curses库
工具/原料
方法/步骤
2接下来是自己写的一个getch函数,注:getch函数在Linux下,不能用。如下:
7#include #include #include int main(){ char passWord[20]; printf('请输入密码:\n'); getpasswd(passWord, 20); printf('\n'); printf('你输入的密码是:%s\n',passWord);}/* 自己写的getch()函数,原本此函数在linux下用不了*/int mygetch(){struct termios oldt,newt;int ch;tcgetattr( STDIN_FILENO, &oldt );newt = oldt;newt.c_lflag &= ~( ICANON | ECHO );tcsetattr( STDIN_FILENO, TCSANOW, &newt );ch = getchar();tcsetattr( STDIN_FILENO, TCSANOW, &oldt );return ch;}/* 获取密码*/int getpasswd(char* passwd, int size) { int c; int n = 0; do { c=mygetch(); if (c != '\n'&& c!='\r' && c!=127) { passwd[n] = c; printf('*'); n++; } else if ((c != '\n'|c!='\r')&&c==127)//判断是否是回车或者是退格 { if(n>0) { n--; printf('\b \b');//输出退格 } } }while(c != '\n' && c !='\r' && n < (size - 1)); passwd[n] = '\0'; //消除一个多余的回车 return n; }