2012-03-16 165 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