[ACCEPTED]-Reading a password from std::cin-password-protection
@wrang-wrang answer was really good, but 3 did not fulfill my needs, this is what my 2 final code (which was based on this) look like:
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif
void SetStdinEcho(bool enable = true)
{
#ifdef WIN32
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
if( !enable )
mode &= ~ENABLE_ECHO_INPUT;
else
mode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hStdin, mode );
#else
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !enable )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif
}
Sample 1 usage:
#include <iostream>
#include <string>
int main()
{
SetStdinEcho(false);
std::string password;
std::cin >> password;
SetStdinEcho(true);
std::cout << password << std::endl;
return 0;
}
There's nothing in the standard for this.
In 6 unix, you could write some magic bytes depending 5 on the terminal type.
Use getpasswd if it's available.
You 4 can system() /usr/bin/stty -echo
to disable echo, and /usr/bin/stty echo
to enable 3 it (again, on unix).
This guy explains how to do it without 2 using "stty"; I didn't try it 1 myself.
If you don't care about portability, you 3 can use _getch()
in VC
.
#include <iostream>
#include <string>
#include <conio.h>
int main()
{
std::string password;
char ch;
const char ENTER = 13;
std::cout << "enter the password: ";
while((ch = _getch()) != ENTER)
{
password += ch;
std::cout << '*';
}
}
There is also getwch()
for wide characters
. My advice 2 is that you use NCurse
which is available in *nix
systems 1 also.
Only idea what i have, you could read password 2 char by char, and after it just print backspace 1 ("\b") and maybe '*'.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.