Hide password input on terminal

后端 未结 15 1561
清酒与你
清酒与你 2020-11-22 09:55

I want to mask my password while writing it with *. I use Linux GCC for this code. I know one solution is to use getch() function like this

15条回答
  •  遥遥无期
    2020-11-22 10:30

    Here is my idea, adapted from that of the C++ official site.

    #include 
    #include 
    #include 
    #include 
    #include 
    using namespace std;
    string getpass(const char *prompt, bool showchar = false, char echochar = '*')
    {
        struct termios oi, ni;
        tcgetattr(STDIN_FILENO, &oi);
        ni = oi;
        ni.c_lflag &= ~(ICANON | ECHO);
        const char DELETE = 127;
        const char RETURN = 10;
        string password;
        unsigned char ch = 0;
        cout << prompt;
        tcsetattr(STDIN_FILENO, TCSANOW, &ni);
        while (getchar() != RETURN) {
            if (ch == DELETE) {
                if(password.length != 0){
                    if (showchar) cout << "\b \b";
                    password.resize(password.length() - 1);
                }
            }else {
                password += getchar();
                if (showchar) cout << echochar;
            }
        }
        tcsetattr(STDIN_FILENO,TCSANOW,&oi)
        cout << endl;
        return password;
    }
    

    It will read one character at once and add it to the string and supports showing another character.

提交回复
热议问题