在linux系統下開發C 程序卻會遇到系統不支持conio.h頭文件,無法使用getch()不回顯函數。下面就演示如何構建函數實現數值輸入不回顯。
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <errno.h> #define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL) //函數set_disp_mode用于控制是否開啟輸入回顯功能 //如果option為0,則關閉回顯,為1則打開回顯 int set_disp_mode(int fd,int option) { int err; struct termios term; if(tcgetattr(fd,&term)==-1){ perror("Cannot get the attribution of the terminal"); return 1; } if(option) term.c_lflag|=ECHOFLAGS; else term.c_lflag &=~ECHOFLAGS; err=tcsetattr(fd,TCSAFLUSH,&term); if(err==-1 && err==EINTR){ perror("Cannot set the attribution of the terminal"); return 1; } return 0; } //函數getpasswd用于獲得用戶輸入的密碼,并將其存儲在指定的字符數組中 int getpasswd(char* passwd, int size) { int c; int n = 0; printf("Please Input password:"); do{ c=getchar(); if (c != '/n'|c!='/r'){ passwd[n++] = c; } }while(c != '/n' && c !='/r' && n < (size - 1)); passwd[n] = '/0'; return n; } int main() { char *p,passwd[20],name[20]; printf("Please Input name:"); scanf("%s",name); getchar();//將回車符屏蔽掉 //首先關閉輸出回顯,這樣輸入密碼時就不會顯示輸入的字符信息 set_disp_mode(STDIN_FILENO,0); //調用getpasswd函數獲得用戶輸入的密碼 getpasswd(passwd, sizeof(passwd)); p=passwd; while(*p!='/n') p++; *p='/0'; printf("/nYour name is: %s",name); printf("/nYour passwd is: %s/n", passwd); printf("Press any key continue .../n"); set_disp_mode(STDIN_FILENO,1); getchar(); return 0; }運行結果:

說明:Linux下C編程遇到要輸入密碼的問題,可輸入的時候密碼總不能讓人看見吧,本來想用getch()來解決輸入密碼無回顯的問題的,不料Linux-C中不支持getch(),我也沒有找到功能類似的函數代替,上面這個例子達到了預期的效果。
PS:linux getch()實現代碼如下所示:
#include <termio.h>int getch(void){ struct termios tm, tm_old; int fd = 0, ch; if (tcgetattr(fd, &tm) < 0) {//保存現在的終端設置 return -1; } tm_old = tm; cfmakeraw(&tm);//更改終端設置為原始模式,該模式下所有的輸入數據以字節為單位被處理 if (tcsetattr(fd, TCSANOW, &tm) < 0) {//設置上更改之后的設置 return -1; } ch = getchar(); if (tcsetattr(fd, TCSANOW, &tm_old) < 0) {//更改設置為最初的樣子 return -1; } return ch;}總結
以上所述是小編給大家介紹的Linux系統下解決getch()輸入數值不回顯示問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網網站的支持!
新聞熱點
疑難解答