• 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

    • HWiNFO 8.28 by Razvan Serea HWiNFO (Hardware Information) is a professional hardware information and diagnostic tool supporting latest components, industry technologies and standards. It's targeted to recognize and extract the most possible amount of information about computer's hardware which makes it suitable for users searching for driver updates, computer manufactures, system integrators and technical exteperts too. Retrieved information is presented in a logical and easily understandable form and can be exported into various types of reports. System health monitoring and basic benchmarking available too. HWiNFO32 & HWiNFO64 v8.28 changelog: Extended number of temperatures monitored (for CPUs with up-to 256 cores). Added OSD independent window without title bar. Added workaround for thermal throttling stuck sticky on Arrow Lake-H. Removed taskbar entry for OSD window. Improved support of next-generation AMD server and workstation platforms. Improved I3C bus synchronization on Intel Sapphire Rapids and later CPUs. Fixed sensor monitoring on some ASRock B850 series mainboards. Added support of ITE IT8698E. Enhanced sensor monitoring on GIGABYTE Q870M D3H. Enhanced support of Intel Wildcat Lake. Added monitoring of NVIDIA PCI Express Error Counters. Added AMD Radeon AI Pro R9700. Improved support of Intel Granite Rapids. Download: HWiNFO 8.28 | 17.8 MB (Free for Non-Commercial use) Download: HWiNFO Portable View: HWiNFO Website | HWiNFO Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Helpwire doesn't support sound transfer.
    • Here's your first look at Raycast for Windows, now in beta by David Uzondu Last September, we reported that Raycast, the popular macOS command bar and launcher tool, was set to make its way to Windows in 2025. Since its launch in 2020, Raycast has quickly become the go-to app that people recommend for new Mac users due to its speed, UI, features, and plethora of extensions. People have been begging for a Windows build, and even a Linux one, for a long time. Now, the company has published a YouTube video showcasing the beta on a Microsoft Surface and explaining how you can get your hands on it today. It's all opened by pressing the default hotkey (Alt + Space). This gives you a central command bar to launch apps, run commands, and search for files. You get a lot of the core features right now, like a calculator that handles natural language queries, a full clipboard history manager, and tools for creating text snippets and quicklinks. For example, typing .pdf instantly filters for just PDF documents, and using a forward slash lets you navigate through folder paths directly. Once you find a file, pressing Ctrl + K opens a contextual action menu with options like "Show in File Explorer" or "Copy File." The included calculator is also a powerhouse, handling everything from basic math to natural language queries, like "time in Barcelona" or "days until August 12." The full clipboard history manager is a massive upgrade over the Windows default. It keeps a running log of everything you copy to your clipboard, including blocks of text, links, images, and files. You can open the clipboard history and search through every item you've copied. It also comes with a powerful filtering system. By pressing Ctrl + P, you can filter your history to show only text, images, links, or even just colors. Its Quick AI feature is also included and will be free for everyone during the beta period. That means you can ask it questions and get answers without needing a Pro subscription for now. Quick AI is built on a set of AI models, like GPT-4o mini, which maintains conversational context, allowing for natural follow-up questions, and you can browse your entire chat history. There's also an "AI search" feature, which is listed as coming soon. The most surprising part is the support for third-party extensions right out of the gate. Raycast built its reputation on an extensive library of integrations that connect it to services like Slack, YouTube, and GitHub. While some of these extensions are written for specific macOS features and are not compatible, many of the extensions are written in JavaScript, which means a huge number of them already work from day one on Windows. Image: @alvaniss1g on X As you can guess, the beta is not feature-complete. A lot of the heavy-hitting Pro features are still on the roadmap and are promised to be coming soon. This includes Cloud Sync to keep your settings consistent across machines, as well as the much-loved Raycast Notes feature. If you are a Pro user on Mac looking to switch, you may want to wait a little longer for full parity. Snippet expansion and calendar integration are also on the to-do list for future updates. Getting into the beta is a bit of a process. Access is being managed through a gradual rollout, with priority given to users who signed up for the waitlist announced last year. If you are on the list, you can expect to receive an email soon. And if you don't like the waitlist, your best bet is to find a friend who already has an invite code, as each invited user gets a few extra codes to share. Sorry, Linux users, but there is no word on your build at the moment, and we're not holding our breath.
    • We M$ and our 801 loved partner$ are having a data party !
    • Wise Disk Cleaner 11.2.4 by Razvan Serea Wise Disk Cleaner is a free disk utility designed to help you keep your disk clean by deleting any unnecessary files. Usually, these unnecessary, or junk files appear as a result of program's incomplete uninstalls, or Temporary Internet Files. It is best if these files are wiped out from time to time, since they may, at some point, use a considerable amount of space on your drives. Wise Disk Cleaner, with its intuitive and easy to use interface, helps you quickly wipe out all the junk files. Using the program is indeed easy. It also works fast when both scanning for files and deleting files. The new Wise Disk Cleaner has more advantages: improved performance, better interface and scans/cleans more thoroughly. Wise Disk Cleaner Free provides lifetime free update service and Unlimited Free technical support. The first Slimming System software Wise Disk Cleaner is the first system slimming tool, which will help you to remove Windows useless files that you don't need, such as Korean IME, Windows Sample music, videos, pictures, Installers and Uninstallers of Updates Patches etc. Wise Disk Cleaner 11.2.4 Build 844 changelog: Improved cleaning rules for WPS Office and Mozilla Firefox. Added cleaning support for Jetbrains Pycharm, Jetbrains WebStorm, Jitsi, Visual Studio Code, jv16 PowerTools, Kakao Talk, Kingo Root, Launchy, Layers of Fear, LBRY, League of Legends, Leapfrog Connect, and Leawo Prof Media. Fixed minor bugs from the previous version. Download: Wise Disk Cleaner 11.2.4 | 6.9 MB (Freeware) Download: Portable Wise Disk Cleaner 11.2.4 | 7.3 MB View: Wise Disk Cleaner Home Page | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • Conversation Starter
      Kavin25 earned a badge
      Conversation Starter
    • One Month Later
      Leonard grant earned a badge
      One Month Later
    • Week One Done
      pcdoctorsnet earned a badge
      Week One Done
    • Rising Star
      Phillip0web went up a rank
      Rising Star
    • One Month Later
      Epaminombas earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      537
    2. 2
      ATLien_0
      205
    3. 3
      +FloatingFatMan
      167
    4. 4
      Michael Scrip
      151
    5. 5
      Som
      127
  • Tell a friend

    Love Neowin? Tell a friend!