Password Masking

closed account (y05iz8AR)
Hi guys I just developing a system for my project and i want to mask the password when you input it.That is displaying "*" sings instead of text. The following is my code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
void main()
{
	int count = 1;
	string username;
	string password;

	void maindisplay();

do
{
	cout<<"Enter User Name - ";
	cin>>username;
	cout<<"Enter Password - ";
	cin>>password;
	cout<<"\n";

	if((username=="aazir") && (password=="aazir"))
	{
		cout<<"Welcome "<<username<<endl;
		cout<<"\n";

		cout<<"Enter Invoice ID - ";
		cin>>invoiceid;

		cout<<"Enter Name - ";
		cin>>name;

		count=4;

		maindisplay();
	}
	else
	{
		cout<<"Incorrect Password.Please check the user name & password, and re-enter."<<endl;
		count++;
	}

}while(count<=3);


}
There is nothing in the standard library which will do that. On windows, you can use <conio.h> to mask input (http://en.wikipedia.org/wiki/Conio.h describes the functions pretty well; note that it only works with Borland, MinGW and VC) and on *nix you can use curses (http://www.gnu.org/software/ncurses/ncurses.html)
closed account (y05iz8AR)
I am using visual studio 2010. I read some where where you can use getch. But i have no idea how to.
_getch() returns the character when a key is pressed, so you could do something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <conio.h>
using namespace std;

char c;
string password;
// loop condition: get a character, while it isn't a newline (end of password), then...
while ((c=_getch()) != '\n')
{
// put it onto the back of the password
    password.push_back(c);
// output a '*' character
    _putch('*');
}
Last edited on
closed account (y05iz8AR)
SO how can i mask the password input here
_getch() will return when a key is pressed by nothing will happen on the screen - so the user won't see anything.

When _getch() returns, if you output a '*' to the screen (_putch()), what the user will see is a key being pressed and a '*' appearing onscreen - so if you typed

password

you would see

********

The following code workes in gcc. Check it out!-
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include<cstdlib>
#include<cstring>
#include<conio.h>

int main()
{
 std::string a="";
 std::string b="ABCD";
 char c;
 for(int i=0;i<1000;i++)
	{
	 c=getch();
	 if(c=='\r')
		break;
	 std::cout<<"*";
	 a+=c;
	}
 if(a==b)
	std::cout<<"Password Matched!!!";
 else
	std::cout<<"Password Incorrect!!!";
return 0;
}

If you want that there be a facility to change the password at runtime, then use file-handling. Save the desired password in a .dat or .txt file and write a function to truncate the fle and enter the new password.
closed account (y05iz8AR)
Thanks Guys.
Topic archived. No new replies allowed.