如何显示星号(*)而不是密码c++的纯文本

How do I display star(*) instead of plain text for password c++

本文关键字:c++ 密码 文本 何显示 显示      更新时间:2023-10-16

如何在C++中显示星号(*)而不是纯文本作为密码。

我在问密码,它是在屏幕上的普通通行证。

如何将它们转换为星号(*),以便用户在输入时看不到密码。

这就是我目前拥有的

        char pass[10]={"test"};
        char pass1[10];
        textmode(C40);
        label:
        gotoxy(10,10);
        textcolor(3);
        cprintf("Enter password :: ");
        textcolor(15);
        gets(pass1);
        gotoxy(10,11);
        delay(3000);
        if(!(strcmp(pass,pass1)==0))
        {
          gotoxy(20,19);
          textcolor(5);
          cprintf("Invalid password");
          getch();
          clrscr();
          goto label;
        }

感谢

您需要使用无缓冲的输入函数,如curses库提供的getch (),或操作系统的控制台库。调用此函数将返回按键字符,但不会返回。使用getch ()读取每个字符后,可以手动打印*。如果按下退格键,您还需要编写代码,并适当更正插入的密码。

这是我曾经用诅咒写的一个代码。用gcc file.c -o pass_prog -lcurses 编译

#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
#define ENOUGH_SIZE 256
#define ECHO_ON 1
#define ECHO_OFF 0
#define BACK_SPACE 127
char *my_getpass (int echo_state);
int main (void)
{
  char *pass;
  initscr ();
  printw ("Enter Password: ");
  pass = my_getpass (ECHO_ON);
  printw ("nEntered Password: %s", pass);
  refresh ();
  getch ();
  endwin ();
  return 0;
}

char *my_getpass (int echo_state)
{
  char *pass, c;
  int i=0;
  pass = malloc (sizeof (char) * ENOUGH_SIZE);
  if (pass == NULL)
  {
    perror ("Exit");
    exit (1);
  }
  cbreak ();
  noecho ();
  while ((c=getch()) != 'n')
  {
    if (c == BACK_SPACE)
    {
      /* Do not let the buffer underflow */
      if (i > 0)
      { 
        i--;
        if (echo_state == ECHO_ON)
               printw ("b b");
      }
    }
    else if (c == 't')
      ; /* Ignore tabs */
    else
    {
      pass[i] = c;
      i = (i >= ENOUGH_SIZE) ? ENOUGH_SIZE - 1 : i+1;
      if (echo_state == ECHO_ON)
        printw ("*");
    }
  }
  echo ();
  nocbreak ();
  /* Terminate the password string with NUL */
  pass[i] = '';
  endwin ();
  return pass;
}

C++本身没有任何东西支持这一点。示例代码中的函数表明您正在使用curses或类似的函数;如果是,请检查cbreaknocbreak功能。一旦你调用了cbreak,就由你来回应角色,你可以回应任何你喜欢的东西(或者什么都不回应,如果你喜欢的话)。

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
void main()
{
 clrscr();
 char a[10];
 for(int i=0;i<10;i++)
 {
  a[i]=getch();     //for taking a char. in array-'a' at i'th place 
  if(a[i]==13)      //cheking if user press's enter 
  break;            //breaking the loop if enter is pressed  
  printf("*");      //as there is no char. on screen we print '*'
 }
 a[i]='';         //inserting null char. at the end
 cout<<endl;
 for(i=0;a[i]!='';i++)  //printing array on the screen
 cout<<a[i];
 sleep(3);                //paused program for 3 second
}