2012-03-16 163 views
2

當用C語言提問時,有什麼方法可以隱藏用戶輸入嗎? 例如:隱藏用戶輸入,只允許某些字符

char *str = malloc(sizeof(char *)); 
printf("Enter something: "); 
scanf("%s", str);getchar(); 
printf("\nYou entered: %s", str); 

// This program would show you what you were writing something as you wrote it. 
// Is there any way to stop that? 

另一件事,是你怎麼能只允許某些字符? 例如:

char c; 
printf("Yes or No? (y/n): "); 
scanf("%c", &c);getchar(); 
printf("\nYou entered: %c", c); 

// No matter what the user inputs, it will show up, can you restrict that only 
// showing up if y or n are entered? 
+0

側面說明:'字符*海峽=的malloc(的sizeof(字符*));'似乎是錯誤的。 scanf是不安全的讀取C字符串 – 2012-03-16 04:35:20

+1

可能重複[從std :: cin讀取密碼](http://stackoverflow.com/questions/1413445/read-a-password-from-stdcin)(即使OP是沒有詢問密碼輸入,鏈接線程中接受的帖子顯示如何禁用/啓用'終端回聲') – 2012-03-16 04:35:32

+0

忘了提及環境,這是一種posix兼容shell,win console或什麼? 你的終端處理輸入緩衝區和afaik沒有便攜的方式來做到這一點。 – AoeAoe 2012-03-16 04:36:05

回答

0

爲了完整起見:沒有辦法在C.要做到這一點(即,標準,沒有任何特定於平臺的庫或擴展純C)

你沒有說明你爲什麼要這樣做(或在什麼平臺上),所以很難提出相關建議。您可以嘗試a console UI libraryGUI library。你也可以嘗試你的平臺的控制檯庫。 (WindowsLinux

2
#include <stdio.h> 
#include <termios.h> 
#include <unistd.h> 
#include <errno.h> 
#define ECHOFLAGS (ECHO | ECHOE | ECHOK | ECHONL) 
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; 
} 
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(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