• 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

    • Do you have a 365 account? I should have been more clear, I mean free accounts.
    • What?! "May 31 2024 knowledge cutoff"?
    • Amazon Alexa+ now has more than a million users by Aditya Tiwari Amazon's muscled-up voice assistant, Alexa+, has reached a new milestone. A company spokesperson told The Verge that Alexa+ has now crossed one million users. The e-commerce giant introduced Alexa+ earlier this year as its generative AI offering. Why? It's a new trend, and everyone is doing it. According to the company, Alexa Plus offers more natural and free-flowing conversations than its predecessor. You can speak half-formed thoughts using colloquial expressions, and the AI assistant should be able to understand you and provide an answer. Announcing its capabilities, Amazon previously said that you will be able to start a conversation on your Echo device and continue it on your phone, car, or computer. One million may not be a significant number when comparing it with the number of Alexa-enabled devices out there. Amazon revealed earlier this year that there are over 600 million Alexa devices globally. However, the number of Alexa+ users has increased from 'hundreds of thousands' in the previous month. The user base is not as big as that of other names like Gemini and ChatGPT because Amazon is still offering the generative AI assistant through an Early Access program, available to Prime and non-Prime members who own a compatible Echo device. We can find social media posts from different users who have been invited to try Alexa+. While there have been positive reviews from some, the road isn't buttery smooth for others. One user claimed that the early access Alexa+ has problems accessing some temperature sensors the previous version of Alexa would. "I also really dislike how it confidently will tell me something that is incorrect now instead of just saying it doesn't know like it used to tell me," the user added. The upgraded AI voice assistant will cost $19.99 per month, but is being offered for free to Prime subscribers. Alexa+ started rolling out in the US as part of its early access program. One reason why Amazon is giving Alexa+ a slow rollout is that the new devices and services chief, Panos Panay, wants to eliminate all the problems related to the generative AI assistant. Amazon's spokesperson told the publication that the early access program doesn't include features like brainstorming gift ideas, scheduling your next spa visit, ordering groceries hands-free, and jumping to your favorite scene on Fire TV. The program also doesn't offer the "new browser-based experience at Alexa.com," which would put Amazon's AI assistant in line with ChatGPT and Gemini. These missing features will be added in the coming weeks and months, as per the spokesperson, adding that almost 90% of the features are now a part of early access.
    • MSI's 32-inch 4K QD-OLED gaming monitor gets a big price cut for UK gamers and professionals by Paul Hill If you’re a gamer in the UK and looking for a monitor to upgrade to then check out the MSI MPG 321URX QD-OLED 31.5 Inch 4K UHD Gaming Monitor which you can now pick up for just 75% of its recommended retail price. The RRP of this monitor is £1,199, but thanks to this deal, you can get it for just £898.99 for a limited time (purchase link down below). With its 4K display, 240Hz refresh rate, and 0.03ms GTG, you’ll have the edge over other gamers by avoiding lag. At 31.5-inches, it’s the ideal monitor size if you’re sitting up close to it at a desk, you don’t want it too big at such a short range, but you also want to be able to see all the image details so 31.5-inches is a good balance. What makes QD-OLED stand out? There are loads of terms used to describe displays such as AMOLED, OLED, LED, and it can all get a bit confusing. This monitor adds yet another acronym called QD-OLED, which stands for Quantum Dot OLED. For you as a buyer, this means your new monitor has self-emitting pixels that deliver great black levels. It also features an enhanced sub-pixel arrangement for extra sharpness. The 31.5-inch 4K UHD monitor has a 3,840 x 2,160 pixel resolution making it ideal for playing games, but also watching movies in the best quality. Other important features worth mentioning are the 1.07 billion colors (10-bit) that the monitor can produce, its 99% DCI-P3 support, and DisplayHDR True Black 400 certification. All of these things make the monitor produce more accurate colours, potentially making it a good choice for professionals editing videos and photos too. Obviously, games will look good too. MSI has also packed in a fanless graphene heatsink which should help to increase the durability of the monitor long-term. This could extend the time until you need to buy a new monitor, further justifying its almost £900 price tag. Gaming and productivity features It’s not just the hardware that makes this monitor excel for gaming, it also comes with great software enhancements and connectivity options. On the software side, you get the following features: Smart Crosshair: Projects a customizable crosshair onto the screen to improve hip-fire accuracy and iron sights in first-person shooter games. Optix Scope: Gives you a built-in aim magnifier with multi-stage zooming and shortcut keys to quickly switch magnification levels. AI Vision: This automatically enhances brightness and colour saturation, particularly in dark areas of the screen, making it easier to see enemies hiding in shadows or dark corners. If you have two separate systems you want to connect to the monitor at once, you can do so with this monitor thanks to KVM support. You can view both sources with Picture-in-Picture and Picture-by-Picture modes. The MSI MPG 321URX QD-OLED 31.5 Inch 4K UHD Gaming Monitor also supports next-gen consoles with features like HDMI CEC Profile Sync, HDMI Variable Refresh Rate (VRR), and 4K:4K downscaling. In terms of connectivity and ergonomics, you get DisplayPort 1.4a, 2x HDMI 2.1 (CEC), USB Type-C with 90W power delivery, and a USB hub. The monitor uses a tilt-, swivel- & height-adjustable stand that is VESA compatible. Should you buy this monitor? The MSI MPG 321URX QD-OLED 31.5 Inch 4K UHD Gaming Monitor is definitely a product for serious gamers looking for top-tier visual fidelity and performance or content creators who need accurate colours and high resolution. Even with the significant discount, it’s still at a premium price and definitely not for everyone. If you are in one of the groups mentioned, then you should give serious consideration to buying the MSI MPG 321URX QD-OLED 31.5 Inch 4K UHD Gaming Monitor as it's the lowest price the monitor has been at on Amazon to date. MSI MPG 321URX QD-OLED 31.5 Inch 4K Gaming Monitor: £898.99 (Amazon UK) / RRP £1,199 This Amazon deal is U.K. specific, and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon UK deals page here. Get Prime, Prime Video, Music Unlimited, Audible or Kindle Unlimited, free for the first 30 days As an Amazon Associate we earn from qualifying purchases.
  • Recent Achievements

    • 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
    • Week One Done
      elsa777 earned a badge
      Week One Done
    • First Post
      K Dorman earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      533
    2. 2
      ATLien_0
      273
    3. 3
      +FloatingFatMan
      201
    4. 4
      +Edouard
      200
    5. 5
      snowy owl
      138
  • Tell a friend

    Love Neowin? Tell a friend!