2009-09-11 86 views
42

我需要從標準輸入讀取密碼,並希望std::cin沒有迴音用戶鍵入的字符...從STD讀取密碼:: CIN

我如何可以禁止的std :: CIN的回聲?

這裏是我目前使用的代碼:

string passwd; 
cout << "Enter the password: "; 
getline(cin, passwd); 

我在尋找一個與操作系統無關的方式來做到這一點。 Here有兩種方法可以在Windows和* nix中執行此操作。

+0

http://stackoverflow.com/questions/13687769/how-to-get-a-password-input-in-c-console-application/13687770#13687770 – 2012-12-03 17:07:41

回答

50

@ wrang-wrang答案是真的很不錯,但並不能滿足我的需求,這是我最後的代碼(這是基於this)看起來像:

#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 
} 

使用範例:

#include <iostream> 
#include <string> 

int main() 
{ 
    SetStdinEcho(false); 

    std::string password; 
    std::cin >> password; 

    SetStdinEcho(true); 

    std::cout << password << std::endl; 

    return 0; 
} 
10

標準中沒有任何內容。

在unix中,您可以根據終端類型編寫一些魔術字節。如果可用,則使用getpasswd

你可以system()/usr/bin/stty -echo來禁用echo,而/usr/bin/stty echo來啓用它(再次,在unix上)。

This guy explains如何做到這一點,而不使用「stty」;我沒有自己嘗試。

+0

我想'getpasswd'確實有幫助。但我正在尋找一種方法來做到這一點,而無需重複操作系統黑魔法 – Vargas 2009-09-11 22:04:57

+2

@Jonathan你提到的第二個鏈接已經死了.. – cbinder 2014-06-27 08:50:22

2

只知道我有什麼,你可以通過字符讀取密碼字符,並在它後面只是打印退格(「\ b」),也許'*'。

+4

如果有人將終端輸出記錄到一個文件,那麼整個密碼將在那裏。那麼可能不是一個好主意。 – Artelius 2009-09-11 22:14:13

+4

與記錄所有按鍵的人相同的情況:) – IProblemFactory 2009-09-11 22:21:31

+1

這是不安全的,也是一個壞主意。爲了您自己的安全,依靠管道的另一端是不可接受的。並且小心不要通過網絡。並記錄輸出!=記錄按鍵:通常將日誌文件的讀取用戶權限賦予比有權在終端仿真器程序上寫入權限的用戶更多的人,或掛鉤到終端或系統事件或鍵盤驅動程序。 – ignis 2012-10-02 07:48:49

6

如果您不關心可移植性,則可以使用_getch()中的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 << '*'; 
    } 
} 

還有getwch()wide characters。我的建議是,您使用NCurse,這在*nix系統中也可用。