0

Possible Duplicate:
Read a password from std::cin

I'm trying to make a simple password program so I can get familiar with C++, but I'm having a bit of a problem. In this code, I ask the user for a password they choose, and then they enter it. What I want to code to do is hide the input (not replace it with *s), but still show the cursor, and the text above, before, and after the password is entered, like this:

Please enter password: [don't show input]
Please re-enter password: [don't show input]

How can I do this? I'm using Linux, so I won't be able to use any windows libraries (windows.h, etc).

Community
  • 1
  • 1
Predictability
  • 2,919
  • 4
  • 16
  • 12

2 Answers2

4

You cannot do this directly using cin. You have to go "lower". Try calling these functions:

#include <termios.h>

...

void HideStdinKeystrokes()
{
    termios tty;

    tcgetattr(STDIN_FILENO, &tty);

    /* we want to disable echo */
    tty.c_lflag &= ~ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}

void ShowStdinKeystrokes()
{
   termios tty;

    tcgetattr(STDIN_FILENO, &tty);

    /* we want to reenable echo */
    tty.c_lflag |= ECHO;

    tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
Nik Bougalis
  • 10,495
  • 1
  • 21
  • 37
0

You'll want to call tcsetattr and modify the ECHO flag.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720