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

标签 c buffer user-input

有没有办法在 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] = '\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 - 隐藏用户输入,仅允许某些字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9731920/

相关文章:

c++ - gdb: 在 0x2aaaaaaab000 添加的符号文件系统提供的 DSO 中找不到可加载的部分

c++ - 在一个大的二进制文件中搜索,在缓冲区中加载 block

java 。当 userInput 是字符串而不是 int 时如何生成错误消息?

c - C编程中如何用异常过滤掉字符

c++ - 无法轮询 SDL 中的鼠标单击事件

objective-c - Objective-C 的 "strict superset"是 C 的哪种方言?

c - 程序需要加CFLAGS=-D_GNU_SOURCE才能编译,这个应该放哪里?

c - 为什么socket关闭后端口没有立即释放?

file - 文件在 Windows 上填充了数据,但在 Linux 上没有

c# - 如何在 C# 中编码打包结构的非托管缓冲区