c-隐藏用户输入,并且只允许使用某些字符



当在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 <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] = '';  
   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='';  
   printf("nYour name is: %s",name);  
   printf("nYour passwd is: %sn", passwd);  
   printf("Press any key continue ...n");  
   set_disp_mode(STDIN_FILENO,1);  
   getchar();  
   return 0;  
}  

对于linux

为了完整性:在C中没有办法做到这一点。(也就是说,没有任何特定于平台的库或扩展的标准、纯C。)

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

相关内容

  • 没有找到相关文章

最新更新