Hey can someone help me with a code to mask password. To print * when the user enter a value and when they hit backspace it takes back a *. Im having trouble figuring out the code

Recommended Answers

All 4 Replies

Hm, afaik there is no easy way of doing this. I once was messing around with some code, and it stopped a user inputting a wrong character type (so the user couldn't type a char into an int or vice versa). That interacted with the TTY layer (on a linux box)..


Hope it helps :)

It isn't possible with Standard C. You have to learn special function added by the compiler authors for your specific compiler and operating system.

I don't think it is all that hard. Try something like this.

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
#define backSpace 8
#define newLine 13


// you can make it better by passing the length of the password
// and testing for the length as well as newLine.

int GetPassword(char *str);

void main()
{
	char PWORD[10];
	GetPassword(PWORD);
	printf("%s\n",PWORD);
}
int GetPassword(char *str)
{
	int i = 0,end = 0;
	char ch;

	do
	{
		ch=_getch();
		switch (ch)
		{
			case backSpace:
			if (i > 0)
			{
				i--;
				str--;
				printf("\b");
				printf(" ");
				printf("\b");
			}
			break;

			case newLine:
			*str = '\0';
			end = 1;
			break;

			default:
			*str = ch;
			str++ ;
			i++;
			printf("*");
			break;
		};
	}while ((end==0));
	return(1);
}
commented: We don't give full answers here, and we also don't suggest using non-Standard C functions. getch() is not in most compilers. -3

Hello slygoth,
There is a simple way to do this. Initialize a character a and write a=getch(). This would not display the character entered by the user.

char a;
a=getch(); // varable a will have the character entered by the user.The character    
cout<<'*'; // entered by the user will not be displayed. cout<<'*' will put '*' 
           //appearing to the user that character that he entered was masked

Instead of a character, declare varable a as a character array. Put that in for loop(a[1]=getch etc.,). The password that the user enters is masked now.Though getch() is not in ANSI c standard it will work.

commented: We don't suggest using non-Standard C functions. getch() is not in most compilers -3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.