Thread: problem with accepting password

  1. #1
    Registered User
    Join Date
    Jun 2007
    Location
    Mysore, India
    Posts
    14

    Question problem with accepting password

    Hi,

    I'm developing a console application in which I've to accept password from the user. When the user enters the password, I want only the asteriks(*) to appear on the screen or else nothing should appear like in UNIX machines. Kindly give me an idea to implement it both ways.

    Thanks,
    Babu

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    i believe something like this has come up before.. give it a search.

  3. #3
    Deathray Engineer MacGyver's Avatar
    Join Date
    Mar 2007
    Posts
    3,210
    I'm guessing you want a Windows version. Since I already wrote one on these forums but with some errors in checking if the HANDLEs are valid or not, I'll put a corrected one here:

    Code:
    char *getPass(char *szBuffer, size_t len)
    {
    	size_t i;
    	HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE);
    	HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
    	DWORD dwOld, dwNumRead, dwNumWritten;
    	if((hIn != INVALID_HANDLE_VALUE) && (hOut != INVALID_HANDLE_VALUE))
    	{
    		if(GetConsoleMode(hIn,&dwOld))
    		{
    			if(SetConsoleMode(hIn,ENABLE_PROCESSED_INPUT))
    			{
    				for(i=0;i<len-1;i++)
    				{
    					if(ReadConsole(hIn,&szBuffer[i],1,&dwNumRead,NULL))
    					{
    						if(szBuffer[i] == '\r')
    						{
    							break;
    						}
    						else WriteConsole(hOut,"*",1,&dwNumWritten,NULL);
    					}
    					else break;
    				}
    				WriteConsole(hOut,"\n",1,&dwNumWritten,NULL);
    				szBuffer[i] = '\0';
    				SetConsoleMode(hIn,dwOld);
    				return szBuffer;
    			}
    		}
    	}
    	return NULL;
    }
    There's a *nix version floating around somewhere in the same topic. I think it was in the C++ section.

    If you want nothing or spaces instead of *'s, you can alter this function to do that, too.

    Edit: Fixed an important bug where the '\0' wouldn't be properly put in place in some cases.....
    Last edited by MacGyver; 07-12-2007 at 12:12 PM.

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    9
    I think you can use the c++ getch() with accepts a character without displaying it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A tenet connection from a C program..
    By ahmd2080 in forum Linux Programming
    Replies: 2
    Last Post: 07-04-2009, 03:42 AM
  2. Password Program
    By lukesowersby in forum C Programming
    Replies: 2
    Last Post: 03-23-2009, 11:36 AM
  3. Laptop Problem
    By Boomba in forum Tech Board
    Replies: 1
    Last Post: 03-07-2006, 06:24 PM
  4. Replies: 5
    Last Post: 11-07-2005, 11:34 PM
  5. Bin packing problem....
    By 81N4RY_DR460N in forum C++ Programming
    Replies: 0
    Last Post: 08-01-2005, 05:20 AM