密码应打印在*

时间:2015-03-07 13:03:43

标签: c

在此功能中,如果用户想要使用该功能,那么它将要求输入密码,即 crackneedit 。当用户输入密码时,它将被打印在屏幕上

所以我希望每当有人输入密码时,都会以*(星号)打印。我应该使用哪种技巧?

int pvote()
{
    int check;
    char *str = "crackneedit";
    char pass[11];
    printf("Enter your password: ");
    scanf("%s",pass);

    check = strcmp(pass,str);
    if (check == 0)
    {
        printf("\nVote recorded according to parties are:\n");
        printf("PARTY               VOTE\n\n");
        printf("BJP                 %d\n",b);
        printf("CONGRESS            %d\n",c);
        printf("AAP                 %d\n",a);
        printf("OTHER               %d\n",o);
        getch();
        return(0);
    }
    printf("\nACCESS DENIED\n");
    return(0);
}

2 个答案:

答案 0 :(得分:1)

你应该使用的技巧是告诉操作系统停止回显键盘输入,而是自己回显每个角色。

这是您的操作系统通常处理键盘输入,直到输入整行文本,在屏幕上回显这些字符;然后将输入的整行输入发送到您的应用程序。您需要进行适当的系统调用以关闭已处理的键盘输入,并让操作系统将每个键入的字符发送到您的进程(包括光标键,回车键等)。

这样做的详细信息完全取决于您的操作系统。由于您忽略了提及您正在使用的操作系统,因此无法提供进一步的建议。

我还要提一下,你需要在你的应用程序中做更多的事情。例如,您无法使用scanf()。您必须编写代码来处理每个键入的字符,一次一个,手动回显每个字符;自己处理退格,构建字符缓冲区等...

答案 1 :(得分:1)

如果我没错,你可以使用termcaps

每当您检测到(例如read)输入时,请将其存储在代码中的char *中,然后在该字词上打印*

这是最终版本:

#include <unistd.h>
#include <termios.h>
#include <stdio.h>

int                     getch()
{
  struct termios        oldtc, newtc;
  int                   ch;

  tcgetattr(STDIN_FILENO, &oldtc);
  newtc = oldtc;
  newtc.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
  ch = getchar();
  tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
  return ch;
}

int             main(int argc, char **argv)
{
  int           c;
  char          ch[20];
  int           i = 0;

  printf("What's your password ?(20 char max.)\n");
  while ((c = getch()) != '\n')
    {
      printf("*");
      ch[i++] = c;
    }
  ch[i] = '\0';
  printf("\nYour password is : [%s]\n", ch);
  return 0;
}

示例:

#include <unistd.h>
#include <termios.h>
#include <stdio.h>

int                     getch()
{
  struct termios        oldtc, newtc;
  int                   ch;

  tcgetattr(STDIN_FILENO, &oldtc);
  newtc = oldtc;
  newtc.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newtc);
  ch=getchar();
  tcsetattr(STDIN_FILENO, TCSANOW, &oldtc);
  return ch;
}

int             main(int argc, char **argv)
{
    int           ch;

  printf("What's your password ?\n");
  while ((ch = getch()) != '\n') // Read 'till you'll type a newline     
      {
      printf("*"); // Print a * instead of what you'll type              
      // Need to store the ch into a char * or whatever.                 
    }
  printf("\n");
  return 0;
}
相关问题