• 0

[C++] Displaying Asterisk's for Password Characters ("*")?


Question

I have recently been developing a program incorporating all the theory we learnt in the first year of university & it is going really well. However, I have a problem with my username & password code (something we never did in my first year).

I have a couple of minor problems but the only one I think I need help with is getting the password characters to all display as "*", in order to maintain privacy. I would like them to behave like actual characters so, for example, if I pressed backspace, I would want it to delete the last character & not display another asterisks.

I have not been able to find a solution to my problem anywhere. So please may somebody help?

I'd rather not change the whole code of my username & password function as I am happy with it at the moment, so would somebody please help me with how to implement this within my current code?

If I have to change the username & password function then I am willing to do so. Also, would anybody like me to display more of my code on this matter?

The following is the function which allows the user to enter the password (but not the whole of my username & password code as that is scattered around the program). I would assume it would have something to do with this line:

 cin >> password;

The whole function works perfectly as it should, I'd just like the password to be displayed with asterisk's :)

Here is my code anyway:

void authorisation(int& keyPressed, int& currentMonth, int& currentYear)
{
	 int getKeyPress();
	 void displayHeaderFooter( int& currentMonth, int& currentYear);
	 void loginSuccess(int& keyPressed, int& currentMonth, int& currentYear);

	 CLEAR_SCREEN();

	 displayHeaderFooter(currentMonth, currentYear);

	 ifstream Passfile("password.txt", ios::in);
	 Passfile >> inputPassword;
	 ifstream Userfile("username.txt", ios::in);
	 Userfile >> inputUsername;
   	 Gotoxy(24, 12);
	 SelectTextColour( clCyan);
	 cout << "Please enter your username.";
	 Gotoxy(42, 10);
	 cin >> username;
	 Gotoxy(24, 13);
	 SelectTextColour( clDarkCyan);
	 cout << "Please enter your password.";
	 Gotoxy(42, 11);
	 cin >> password;
	 Userfile.close();
	 Passfile.close();

	 userHeader = 1;

	 while (username == inputUsername && password == inputPassword)
	 {
		if (userHeader == 1)
		{
		Gotoxy(0, 0);
		SelectTextColour( clGrey);
		SelectBackColour( clDarkCyan);
		cout << "		" << username << "		  ";
		}

		 Gotoxy(23, 18);
		 SelectTextColour( clGreen);
		 SelectBackColour( clBlack);
		 cout << "You have logged in successfully.";
		 Gotoxy(15, 19);
		 cout << "Please press the 'M' key to display the Main Menu.";
		 loginSuccess(keyPressed, currentMonth, currentYear);
	 }


	 if (username != inputUsername || password != inputPassword)
	 {
		 Gotoxy(16, 18);
		 SelectTextColour( clRed);
		 cout << "\a";
		 cout << "The username or password you entered is invalid.";
		 Gotoxy(21, 19);
		 cout << "Please press the 'L' key to try again.";
		 keyPressed = getKeyPress();
		 if (keyPressed == 'L')
		 {
			 authorisation(keyPressed, currentMonth, currentYear);
		 }
		 else
		 {
			Gotoxy(16, 18);
			SelectTextColour( clRed);
			cout << "\a";
			cout << "	" << "The command you entered is invalid." << "	";
			Gotoxy(21, 19);
			cout << "	" << "Please press the 'L' key to login." << "	";
		 }
	 }

}

Thank you in advance. I would be very grateful for any help :)

Edited by cJr.

8 answers to this question

Recommended Posts

  • 0

cin is buffered so you'll have to use the raw file description functions to get the effect you want. Unfortunately, this type of stuff is non-standard, so you'll have to specify which OS your compiling/running this code on for us to better help you.

  • 0

Thank you for your help & advice, although I don't really understand what you said (I'm still a beginner :()

I am using Windows Vista & at the moment I'm looking to make this application Windows only. It is a Win32 console application & I am using Visual Studio 2005 (rather than DevC++ or anything which sometimes have their own libraries).

Is there any more information you need?

  • 0

Here is how to do it on windows, with example code:

http://msdn.microsoft.com/en-us/library/078sfkak.aspx

----------------------

When I say cin is buffered, it means that when you press a key, the stuff your typing is stored in a buffer until you press the enter key.

An unbuffered input means that when you press a key, that value goes straight into the variable your using to store what's inputted.

A file descriptor is simply an integer that points to some input or output in the file descriptor table in the kernel, which has the actually address of the file (on disk or in memory) and other options

For example,

when you do something like:

FILE *j;

j = fopen('abc.txt', 'r');

You are essentially get back a integer, like 3. Then in the kernel there is a structure that has something like:

0 stdin 0x00203040

1 stdout 0x02340230

2 stderr 0x23423409234

3 "abc.txt" 0x20340304

This is a very simplistic view, but I think you'll get the idea.

  • 0

I guess that will need its own routine, which you'll call from the authorisation routine. You'll have a loop that goes over each character using the aforementionned _getch_, and which will use a buffer (hm... maybe a vector<char>?) to, well, buffer all the characters and return a string when the enter key is pressed. Then if you want asteriks you just have to display a number of asteriks equal to the length of the buffer.

I'm not sure how you would implement the backspace functionality though.

  • 0

Thank you both dduardo & Dr_Asik. There are a fair few things I don't understand completely in both your posts, however, I will have a look at them in detail when I get chance & research the parts I don't understand.

I will get back to you when I have had time to look at what you've said & try a few things (if I end up understanding how to implement the _getch(); code into my code lol :s)

  Joel said:
The word you were looking for is 'asterisk'. Asterix is a comic book character.

Thank you for informing me Joel. I'm surprised because my English is normally very good (especially as I didn't pick it up on Firefox's spell-checker either) :p

  • 0
  Dr_Asik said:
I'm not sure how you would implement the backspace functionality though.

The easiest way to implement a password protection system is to simply don't print anything and ask for the password two times. This is how 99.99% of the command-line utilities do it.

But if you really want the asterisk blocked password you see in web-browsers than things get a little bit more complicated.

You'll want to use setConsoleCursorPosition and include 'windows.h'

http://msdn.microsoft.com/en-us/library/ms686025(VS.85).aspx

And do something like this:

COORD coord;

coord.X = x; coord.Y = y;

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);

COORD is just a struct with x and y members

When ever you get a backspace code you'll move the cursor position back one and then write a space, then move the cursor back to the space to overwrite it when the user enters another character.

It seems like +cJr. is using some other library that uses gotoxy and has other console functions, but those aren't windows.h stuff, atleast from what i've found on msdn.

Edited by dduardo
This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • There is nobody to challenge the status quo. Foldables have not taken off as expected. People are holding onto their existing phones for a lot longer. There is movement happening in the handheld console space, but those are not phones. Both Apple and Google are involved in legal fights. Yet they have to stick to releasing a new OS every year... It all adds up.
    • Elon Musk once again claims Tesla robotaxis are coming soon by David Uzondu Image via Depositphotos.com Tesla's CEO, Elon Musk, has announced a tentative start date of June 22 for the company's long-awaited public robotaxi service. According to a post on his social media platform X, the initial launch will be in Austin, Texas. Musk added a significant condition, however, saying "We are being super paranoid about safety, so the date could shift." The service is expected to begin with just 10 to 20 Model Y SUVs operating within a limited area and with remote human supervision. He also mentioned a plan starting June 28 for new Teslas to drive themselves from the factory to a customer's home. This is a moment many are probably waiting for, though it comes with a heavy dose of skepticism. Musk has made grand promises about self-driving before. This robotaxi network brings to mind the bold claims from all the way back in 2019 when the company said a similar service would launch the following year. That evidently did not happen. Federal regulators also have their doubts. Last year, the National Highway Traffic Safety Administration criticized Tesla for making its "Full Self-Driving" feature sound more capable than it actually is, demanding the company align its marketing with reality. Tesla is also driving into a field that is no longer empty. Waymo, Google's sibling company, is already a major player, offering hundreds of thousands of paid rides per week across Phoenix, San Francisco, Los Angeles, and even Austin. The company is so far ahead that it has begun testing in Tokyo. But being ahead means Waymo is also the first to face certain dangers. For example, on the evening of June 8, a group of protesters in downtown Los Angeles summoned Waymo vehicles during a demonstration. When the vehicles arrived, they slashed the tires, smashed the windows, and spray-painted the cars before setting three of them on fire. Which raises a thorny question for Tesla: if you can summon a car with no one inside, can you summon it just to destroy it? It's one thing for protesters to stumble upon a robotaxi and vandalize it; it's another for someone to use the app to call a driverless car to a secluded spot for a planned attack. With public sentiment around Musk so divided, especially given his DOGE shenanigans and his recent face off with Donald Trump, that's not just a theoretical problem. We've already seen this hostility play out in attacks where people vandalize Teslas, carving swastikas into them and spray painting slogans like "Burn More Teslas" on walls.
    • This is actually quite useful. But why wouldn't they implement this in the local file system? The code is obviously all there now... maybe in 5 years.
    • The new "Story Cards" in the Software section are nice, but I wish they had the product icon included. I use this section to identify updates for software that I use regularly, and it's sometime difficult to identify the software without the product icon. Thanks for your consideration. pelaird
    • Mozilla really needed to focus on their core product for a while now. I will not mourn the death of pocket or AI garbage. One thing they don't do that I believe they should is advertise more, and not just to their core audience, especially their additional services. Let people know they actually exist.
  • Recent Achievements

    • Week One Done
      Food-Beverages-Nutrition earned a badge
      Week One Done
    • Week One Done
      Tech Dogs earned a badge
      Week One Done
    • Enthusiast
      computerdave91111 went up a rank
      Enthusiast
    • Week One Done
      Falisha Manpower earned a badge
      Week One Done
    • One Month Later
      elsa777 earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      524
    2. 2
      ATLien_0
      271
    3. 3
      +Edouard
      199
    4. 4
      +FloatingFatMan
      196
    5. 5
      snowy owl
      138
  • Tell a friend

    Love Neowin? Tell a friend!