隐藏用户输入,仅允许某些字符

有什么方法可以在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? 

  #include  #include  #include  #include  #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

为了完整起见: 在C中没有办法做到这一点。 (即标准的普通C,没有任何特定于平台的库或扩展。)

你没有说明你为什么要这样做(或在什么平台上),所以很难提出相关的建议。 您可以尝试控制台UI库或GUI库 。 您也可以尝试平台的控制台库。 ( Windows , Linux )