• 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

    • Mixed news. Glad to hear LibreOffice is catching up to MS's Office. The latter has become way too bloated/complicated and non-intuitive to non-power users. Apparently, MS no longer cares for the non-gaming home-based consumer. Sad to hear support for WIndows-7 is ending. Many users remain with Windows-7 as it was easy to use, intuitive, and reliable. Non-power users and gamers don't need to needless complexity, dubious "features," and long-term instability of the last few versions. [After "how many years" Windows-10 is now reasonably stable--as long as MS stops mucking with it.]
    • Yeah but Microsoft actually did a good job with Aero Glass. I remember the only complaints was about how people could not use it without a top tier card back in the day, it would also disable until you activated Windows. Aero Glass was used in window borders, taskbar and yes the Start menu, but only as a border reference, the programs in the Start menu had a black background on Start (if I remember correctly) and All Programs and context menus were not glass.
    • The only thing it looks like to me is harder to read.
    • I am surprised that the kid who got run over next to stop light did not sue...
    • Wine 10.10 released, brings updated Mono engine, bug fixes for several games, and more by David Uzondu Nearly two weeks after Wine 10.9 dropped, Wine 10.10 is here with an updated Mono engine and the complete removal of a major graphics dependency. The Wine Mono engine, which provides .NET Framework support, has been bumped to version 10.1.0. Another major change is the removal of the OSMesa library as a dependency. OpenGL rendering on memory device contexts will now be handled by a pbuffer, cleaning up the graphics stack. Here are other notable changes with this release: More support for generating Windows Runtime metadata in WIDL. Locale data updated to Unicode CLDR 47. P010 format support in Media Foundation. Of course, no development release would be complete without a boatload of bug fixes. This version crushes a total of 38 bugs, addressing problems in a wide range of applications and games. Gamers will be pleased to see fixes for titles like F.E.A.R., S.T.A.L.K.E.R.: Anomaly, and StarCraft Remastered. Issues that caused a black screen in Steam's Big Picture mode and crashes when starting a new game in F.E.A.R. have been resolved. The fixes go way back, even tackling issues in ancient software like Lotus Freelance Graphics 2.1 and input problems in the classic indie game Braid. Here's the full list of game-related issues addressed: Rise of Nations: Both mouse buttons were required for a single left-click Braid: Both Shift keys needed to move puzzle pieces F.E.A.R: Crashed with an "Out of memory" error when starting a new game F.E.A.R Combat: Black screen at startup due to memory error S.T.A.L.K.E.R. Anomaly: Crashed when loading into a save file StarCraft Remastered: Game wouldn't start with Wine 10.5 Unreal II: Hangs with a black screen when switching to 1440x900 resolution Eador. Masters of the Broken World: Bad map textures after starting the game Horizon Chase: Freezes on startup The Fidelio Incident and Vampyr: Beeping noise on exit Burger Shop: Shifted to the top left corner in fullscreen mode And here's the rest of the issues that were fixed: Lotus Freelance Graphics 2.1: Hangs at the splash screen HTML-Kit 292: Tab bar isn't fully visible without scrolling at 96 DPI Tab completion for cmd: Improvements made regedit: Binary values editor layout is broken and .reg files couldn’t be imported Baofeng5-5.31.1128: Welcome window crashes on start Canon printer driver installation now works Steam Big Picture mode: Fixed black screen when using d3d10 Noteworthy Composer: Crashes in winealsa resolved Ricoh Digital Camera Utility 5: Crashes when switching between Browser and Laboratory modes Wondershare Uniconverter 13: Characters now display properly AVCLabs Video Enhancer AI: No longer crashes on start New thread stack memory usage optimized PlayOnline Viewer: Window now properly activates after being minimized Virtual desktop behavior fixed secur32:ntlm tests now pass on Windows 11 24H2 d3d9:device WM_WINDOWPOSCHANGED test no longer fails on Linux GitLab CI no longer crashes in various multimedia tests HP Prime Virtual Calculator: Fixed startup crash Qt Installer for Windows: Now functions correctly SHIFT-based range selection logic corrected Creating 64-bit wineprefix with old wow64 now possible Regression from realloc switch fixed (memory now zeroed as expected) RTTI now works on arm32 after recent changes Smartsuite 3.1 installer no longer crashes Fixed possible use-after-free in dbghelp's symt_add_func_line Build issues with clang for x86_64 resolved due to RTTI changes You can read the full release notes here. The source code for this release is also available. To get started, follow the installation instructions for your platform: Ubuntu/Debian, Fedora, or macOS.
  • Recent Achievements

    • Week One Done
      Simmo3D earned a badge
      Week One Done
    • One Month Later
      Simmo3D earned a badge
      One Month Later
    • One Month Later
      greege earned a badge
      One Month Later
    • Week One Done
      greege earned a badge
      Week One Done
    • Week One Done
      LagFighterZ earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      547
    2. 2
      ATLien_0
      232
    3. 3
      +FloatingFatMan
      165
    4. 4
      Michael Scrip
      119
    5. 5
      +Edouard
      91
  • Tell a friend

    Love Neowin? Tell a friend!