How can I do so that I can display star(*) instead of plain text for password in C++.
I am asking for password and it is plain pass on the screen.
How can I convert them in to star(*) so that user can not see the password while entering.
This is what I have currently
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;
}
Thanks
You need to use an unbuffered input function, like getch ()
provided by curses library, or a console library of your OS. Calling this function will return the pressed key character, but will not echo. You can manually print *
after you read each character with getch ()
. Also you need to write code if backspace is pressed, and appropriately correct the inserted password.
Here is a code which once i wrote with the curses. Compile with 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] = '\0';
endwin ();
return pass;
}
There's nothing in C++ per se to support this. The functions in your example code suggest that you are using curses
, or something similar; if so, check the cbreak
and nocbreak
functions. Once you've called cbreak
, it's up to you to echo the characters, and you can echo whatever you like (or nothing, if you prefer).
#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]='\0'; //inserting null char. at the end
cout<<endl;
for(i=0;a[i]!='\0';i++) //printing array on the screen
cout<<a[i];
sleep(3); //paused program for 3 second
}
精彩评论