how to display * for input password

how to display * when user is require to input the password?
Last edited on
That is a system-dependant thing to do. What OS are you using?

If you want something more platform-independant, check out NCurses (unix) and PDCurses (windows).
I did it like that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(){
   string pass ="";
   char ch;
   cout << "Enter pass\n";
   ch = _getch();
   while(ch != 13){//character 13 is enter
      pass.push_back(ch);
      cout << '*';
      ch = _getch();
   }
   if(pass == "Mitsakos"){
      cout << "\nAccess granted :P\n";
   }else{
      cout << "\nAccess aborted...\n";
   }
}


Isn't it right?
Isn't it right?

It's a MS-Dos/Windows only solution, since _getch() is defined in conio.h which is MS specific. Plus, it isn't secure. Now the question is: should it be? Or should it just look neat? If it really is a password input, it certainly should be. In which case you need platform specific functions anyways (but not _getch()). Read the documentation of your OS-API for details.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <conio.h>
using namespace std;
int main(){
   string pass ="";
   char ch;
   cout << "Enter pass\n";
   ch = _getch();
   while(ch != 13){//character 13 is enter
      pass.push_back(ch);
      cout << '*';
      ch = _getch();
   }
   if(pass == "Mitsakos"){
      cout << "\nAccess granted :P\n";
   }else{
      cout << "\nAccess aborted...\n";
   }
}


Could you please explain me that part of your code as i am working on a similar program and thought why not ask in this thread rather than creating a new one.

And one more thing. I work on Turbo C++.
Last edited on
If conio.h is only from MS i don't know if it will work with Turbo C++.

But anyway here is how I thought about it.
the _getch() function wait's for an input from the keyboard but doesn't show the key to the console.

ch = _getch(); Reads a keystoke and saves it to the ch, but doesn't display it in the console.

while(ch != 13){ As long as the user doesn't press Enter (enter is ASCII code 13) continue reading keystrokes from the screen.

pass.push_back(ch); The pass is a string variable. The push_back() method puts the character specified as parameter at the end of the string.
http://www.cplusplus.com/reference/string/string/push_back.html

cout << '*'; Since nothing has been displayed from the keystroke we display an asterisk ( '*' ) for every key.

ch = _getch(); You read another keystroke to continue reading keystrokes from the user.


I don't know if you need anything else. Hope this helps.
conio.h should be included in the OS API, as far as I know, so work under any compiler in Windows.
Last edited on
conio.h is an old Borland extention for Turbo C/C++ (which only works on 16-bit DOS and emulators), and is very much deprecated in modern compilers.

If you know you will be sticking to Windows development, you can change the console input mode to do your bidding.

Also, stay away from directly coding ASCII values. It probably won't hurt, but it could someday... so it is considered bad practice.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <stdexcept>
#include <string>
#include <windows.h>
using namespace std;

string getpassword( const string& prompt = "Enter password> " )
  {
  string result;

  // Set the console mode to no-echo, not-line-buffered input
  DWORD mode, count;
  HANDLE ih = GetStdHandle( STD_INPUT_HANDLE  );
  HANDLE oh = GetStdHandle( STD_OUTPUT_HANDLE );
  if (!GetConsoleMode( ih, &mode ))
    throw runtime_error(
      "getpassword: You must be connected to a console to use this program.\n"
      );
  SetConsoleMode( ih, mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) );

  // Get the password string
  WriteConsoleA( oh, prompt.c_str(), prompt.length(), &count, NULL );
  char c;
  while (ReadConsoleA( ih, &c, 1, &count, NULL) && (c != '\r') && (c != '\n'))
    {
    if (c == '\b')
      {
      if (result.length())
        {
        WriteConsoleA( oh, "\b \b", 3, &count, NULL );
        result.erase( result.end() -1 );
        }
      }
    else
      {
      WriteConsoleA( oh, "*", 1, &count, NULL );
      result.push_back( c );
      }
    }

  // Restore the console mode
  SetConsoleMode( ih, mode );

  return result;
  }

int main()
  {
  try {

    string password = getpassword( "Enter a test password> " );
    cout << "\nYour password is " << password << endl;

    }
  catch (exception& e)
    {
    cerr << e.what();
    return 1;
    }

  return 0;
  }

This is not secure. A keylogger can spy on what you type. (This is,
sadly, fairly normal. I don't know of any specific Win32 API function that
will securely read a password, but I know that the OS has one in there somewhere...)

Hope this helps.

[edit] Fixed a bug.
Last edited on
as far as i know a keylogger will ALWAYS catch ur input... it may simulate the driver...
If you've let a keylogger get that kind of access to your system, then yes, you are royally screwed.

But for lesser softwares you can disable all hooks, etc. to prevent peeking. Failure to do so means even low-access software can hook and peek.

Alas.
Hi,
I am Rammohan from Bangalore and working as a Technical lead in big IT firm .
Solution for your answer is follows:


I believe you are a student and so I have written the following code to compile in TurboC. Since you people are using Turboc in your institutes. If you want the solution to work for other compiler or any other platform also please ask me and I will definitely send you in my way of code to work in all the platforms…

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
cout<<"Enter password: \n";
restart:int x[100],x1[100],i,j=0,k=0,l;
for(i=0;i<=100;i++)
{
Rammohan:l=getch();
if(((l>=48)&&(l<=126))||(l==8)||(l==13))
x[i]=l;
else goto Rammohan;
if(x[i]==13)
break;
else if(x[i]==8)
{
gotoxy(1,2);
clreol();
for(i=0;i<100;i++)
x[i]='\0';
goto restart;
}
else
{
cout<<"*";
k++;
}
}
cout<<"\nRe enter password: \n";
for(i=0;i<=k;i++)
{
x1[i]=getche();
if(x1[i]==13)break;
}
for(i=0;i<=k;i++)
if(x[i]!=x1[i])
j++;
if(j==0)
cout<<"\nPasswords match!!\n";
else cout<<"\nPasswords do not match!!\n";
getch();
}
____________________
Regards,
Rammohan Alampally,
[email protected]
Technical Lead,
Bangalore, India.
www.FindSyntax.com -> Worlds first Web based Windows O/S is a Brain Chaild of Rammohan
omg... may u use the [code]-brackets plz... mr-big-it ... nice english :P...
*sigh*
nice
do someone know solution to hide entered character to console in linux?
Rammohan, could you help me with this? ;)
Whether in Windows or Linux, you still need to set the keyboard to no-echo, unbuffered input. Here's an example of how to do that in linux:
http://www.cplusplus.com/forum/beginner/1988/page4.html#msg14522

Once you are in raw mode, use the same method as above to get the input and display *s.

Good luck!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<iostream.h>
#include<conio.h>
void main()
       {
             clrscr();
             cout<<"Enter password: \n";
             restart:int x[100],x1[100],i,j=0,k=0,l;
             for(i=0;i<=100;i++)
                 {
                     Rammohan:l=getch();
                     if(((l>=48)&&(l<=126))||(l==8)||(l==13))
                         x[i]=l;
                     else 
                         goto Rammohan;
                     if(x[i]==13)
                         break;
                    else if(x[i]==8)
                           {
                             gotoxy(1,2);
                             clreol();
                                for(i=0;i<100;i++)
                                    x[i]='\0';
                                goto restart;
                     }
else
{
           cout<<"*";
           k++;
}
}
cout<<"\nRe enter password: \n";
for(i=0;i<=k;i++)
    {
          x1[i]=getche();
          if(x1[i]==13)break;
    }
for(i=0;i<=k;i++)
     if(x[i]!=x1[i])
         j++;
     if(j==0)
        cout<<"\nPasswords match!!\n";
     else 
        cout<<"\nPasswords do not match!!\n";
     getch();
}
Well i wrote this code based on the codes posted above.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
	char pass[5];
	int i=0;
	cout<<"\n\n Pass : ";
	pass[0]=_getch();
	while(pass[i]!=13)
	{
		i++;
		cout<<"*";
		pass[i]=_getch();
	}
	
	cout<<"\n\n";
	
	cout<<pass;
	
	getch();


Well the bizarre problem is that if the starting character of the password is 'a' the the output statement "cout<<pass" shows a smiley face (maybe some ASCII value of DOS )instead of 'a' lol?

For ex : Inputted Pass is : abc

Displayed Pass is : smiley-facebc

EDIT : I recently discoverd that if the entered pass is 3 letters only the above mentioned error comes. Can someone explain this to me why ?
This sort of thing doesn't happen if 'a' is anywhere other than the starting character in thr array and the array hold only 3 letters.
Last edited on
Failure to initialize creates a great big surprise.

Include <cstring> and put the following line between lines 2 and 3 above:

memset( pass, 0, 5 );
[edit] Oh, and keep your passwords four characters or less.
Last edited on
Topic archived. No new replies allowed.