C++ password input on BOTH WINDOWS AND LINUX

I want to write a simple command line password input program. When the user input a password, the program must display "*" to cover the password, or do something to hide the password.

I want to compile my program on both Windows XP and Linux, PREFERABLY WITH EXACTLY THE SAME SOURCE CODES.

How to do this?
Last edited on
Since terminal control differs drastically between Windows and Unix, you are left only with using a cross-platform GUI kit such as Qt.

I assume

#ifndef WINDOWS
// do this
#else
// do that
#endif

is out of the question.
Sorry, I forgot to tell that the program is a command line program with no GUI.
You can use conio.h libray for it.
Example :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <cstdlib>
#include <conio.h>

using namespace std ;

int main( void )
{
 	char ch ;
 	do{
	   	 ch = getch();
	   	 if( !iscntrl( ch ) )
	   	 	 putch( '*' );
	}while( ch != '\r' );
 	system( "PAUSE" );
 	return ( 0 );	
}

You can improve this example.
Last edited on
Well, ...

conio.h does not exist in Linux. And getch() exists only in curses; putch() does not exist at all.
You are trying to do something that is platform-dependent with the same code on every platform. By definition that can't be done.

The simplest answer is to simply turn off echo.

On Windows
1
2
3
4
5
6
7
8
9
10
11
12
#include <windows.h>

void echo( bool on = true )
  {
  DWORD  mode;
  HANDLE hConIn = GetStdHandle( STD_INPUT_HANDLE );
  GetConsoleMode( hConIn, &mode );
  mode = on
       ? (mode |   ENABLE_ECHO_INPUT )
       : (mode & ~(ENABLE_ECHO_INPUT));
  SetConsoleMode( hConIn, mode );
  }

On POSIX (Unix, Linux, etc)
1
2
3
4
5
6
7
8
9
10
11
12
#include <termios.h>
#include <unistd.h>

void echo( bool on = true )
  {
  struct termios settings;
  tcgetattr( STDIN_FILENO, &settings );
  settings.c_lflag = on
                   ? (settings.c_lflag |   ECHO )
                   : (settings.c_lflag & ~(ECHO));
  tcsetattr( STDIN_FILENO, TCSANOW, &settings );
  }
You will have to link with one of -lcurses or -ltermios or -lncurses ... whichever is appropriate for your system.

Now, you can turn echo on or off easily
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;

#include "platform-code.hpp"

int main()
  {
  string pwd;
  cout << "Please enter a passcode> ";

  echo( false );
  getline( cin, pwd );
  echo( true );

  cout << "\nYour password is \"" << pwd << "\"\n";
  return 0;
  }


When you compile and link, compile the platform-dependent code that is appropriate for your platform: the windows stuff on windows and the POSIX stuff on Unix/Linux/whatever. If you have other platforms in mind, you will have to write code appropriate for that too. Then link the module into the final executable.

Hope this helps.

[edit] BTW, I didn't test any of this code -- errors may have occurred.
Last edited on
Topic archived. No new replies allowed.