how to put asterisk for password type variables

as stated in the title

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>

using namespace std;

int main()
{
	cout << "\tWelcome to Game Developer!" << endl;

	string loginId = "m.003k";
	string password = "s4_33";
	bool loginSuccess;
	char rollDice;
	char playAgain;
	do
	{

		if ( cin.fail() || loginId == "m.003k" || password == "s4_33" ) 
	cout << "\nUsername: ";
	getline (cin,loginId);

	cout << "Password: ";
	getline (cin,password);

	if ( loginId == "m.003k" && password == "s4_33" )
	{
		cout << "\nLogin success.";
		loginSuccess = true;
	}

	else
	{
		cout << "\nLogin failed.";
		loginSuccess = false;
	}

	}while( cin.fail() || loginId != "m.003k" || password != "s4_33" );

	if ( loginSuccess == true )
	{
		cout << "\nDo you want to roll a dice?(y/n) : ";
		cin >> rollDice;
		do
		{
		if ( rollDice == 'y' )
		{
			srand(static_cast<unsigned int>(time(0)));

			int randomNumber = rand();
			int theDice = (randomNumber % 6) + 1;

			cout << "\nYou have rolled " << theDice <<  ".";

		}
		cout << "\nDo you want to play again?(y/n) : ";
		cin >> playAgain;
		}while( playAgain == 'y' );

		
	}

	    system("pause");
		return 0;
}


how do i make it that when the user type in his/her password it will be an asterisk?

thank you in advance.
std::cout << '\b' << '*';
that is the only idea i would have. the \b is the back/delete button. if you do this you need to do
1
2
3
4
5
6
7
std::string s; 
while(char c != '\n'){
        std::cin >> c;//gets the next char
        s += c; //adds char to end of string
        std::cout << '\b' << '*';//replace with an asterisk 
       //there will be a new line char at the end of the name so make sure to delete that
}
Last edited on
thanks for all the reply.

@long double main, do u have any other articles that give explanation, because my c++ level is only @ the very basic.
WIN32's EDIT class contains this exact feature. It can be enabled quite easily there.

I've never seen a professional console app that does this though. Even telnet, svn, fpt, or ssh commands don't ussually do this. If you were to do it, perhaps using the <curses> library would work well.

EDIT: Actually long double main's solution is really nice and easy. Just copy the getpass() and getch() (if applicable) functions exactly as written. Also don't forget to include the appropriate headers.
Last edited on
Topic archived. No new replies allowed.