簡體   English   中英

從 std::cin 讀取密碼

[英]Reading a password from std::cin

我需要從標准輸入中讀取密碼,並希望std::cin不回顯用戶輸入的字符...

如何禁用 std::cin 的回聲?

這是我目前使用的代碼:

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

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

@wrang-wrang 答案非常好,但沒有滿足我的需求,這就是我的最終代碼(基於)的樣子:

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

標准中沒有任何內容。

在 unix 中,您可以根據終端類型編寫一些魔術字節。

如果可用,請使用getpasswd

您可以 system() /usr/bin/stty -echo禁用回聲,並/usr/bin/stty echo啟用它(再次,在 unix 上)。

這家伙解釋了如何在不使用“stty”的情況下做到這一點; 我自己沒試過。

如果你不關心可移植性,你可以在VC使用_getch()

#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 << '*';
    }
}

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

只知道我有什么,您可以逐個字符讀取密碼字符,然后只打印退格鍵(“\\b”)和“*”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM