Reading a password from std::cin

后端 未结 4 1129
萌比男神i
萌比男神i 2020-11-22 04:46

I need to read a password from standard input and wanted std::cin not to echo the characters typed by the user...

How can I disable the echo from std::c

4条回答
  •  独厮守ぢ
    2020-11-22 05:25

    @wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like:

    #ifdef WIN32
    #include 
    #else
    #include 
    #include 
    #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 usage:

    #include 
    #include 
    
    int main()
    {
        SetStdinEcho(false);
    
        std::string password;
        std::cin >> password;
    
        SetStdinEcho(true);
    
        std::cout << password << std::endl;
    
        return 0;
    }
    

提交回复
热议问题