Hide user input on password prompt [duplicate]
Asked Answered
G

3

22

Possible Duplicate:
Read a password from std::cin

I don't work normally with the console, so my question is maybe very easy to answer or impossible to do .

Is it possible to "decouple" cin and cout, so that what I type into the console doesn't appear directly in it again?

I need this for letting the user typing a password and neither me nor the user normally wants his password appearing in plaintext on the screen.

I tried using std::cin.tie on a stringstream, but everything I type is still mirrored in the console.

Glean answered 1/8, 2011 at 13:23 Comment(1)
See also: github.com/Seldaek/hidden-inputAlarmist
P
42

From How to Hide Text:

Windows

#include <iostream>
#include <string>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
    DWORD mode = 0;
    GetConsoleMode(hStdin, &mode);
    SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main 

cleanup:

SetConsoleMode(hStdin, mode);

tcsetattr(STDIN_FILENO, TCSANOW, &oldt);

Linux

#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>

using namespace std;

int main()
{
    termios oldt;
    tcgetattr(STDIN_FILENO, &oldt);
    termios newt = oldt;
    newt.c_lflag &= ~ECHO;
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);

    string s;
    getline(cin, s);

    cout << s << endl;
    return 0;
}//main 
Phosphoroscope answered 1/8, 2011 at 13:27 Comment(1)
tcsetattr(STDIN_FILENO, TCSANOW, &oldt); is required for cleanup in Linuz too.Monogram
D
5

You're really asking about two unrelated issues.
Calling cin.tie( NULL ) decouples std::cin and std::cout completely. But it doesn't affect anything at a lower level. And at the lowest level, at least under Windows and Unix, std::cin and std::cout are both connected to the same device at the system level, and it is that device (/dev/tty under Unix) which does the echoing; you can even redirect standard out to a file, and the console will still echo input.

How you turn off this echoing depends on the system; the easiest solution is probably to use some sort of third party library, like curses or ncurses, which provides a higher level interface, and hides all the system dependencies.

Driskell answered 1/8, 2011 at 13:36 Comment(0)
A
4

Use getch() to get the input instead of using cin, so the input will not be shown (quoting wiki):

int getch(void) Reads a character directly from the console without buffer, and without echo.

This is really C, not C++, but it might suit you.

Also, there's another link here.

Araiza answered 1/8, 2011 at 13:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.