隐藏用户输入,仅允许某些字符 [英] Hide user input, and only allow certain characters

查看:90
本文介绍了隐藏用户输入,仅允许某些字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中要求时,是否有任何方法可以隐藏用户输入?
例如:

Is there any way to hide user input when asked for in C? For example:

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?

另一件事,如何只允许某些字符?
例如:

Another thing, is how can you only allow certain characters? For example:

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] = '\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

这篇关于隐藏用户输入,仅允许某些字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆