Reading a password from std::cin

后端 未结 4 1177
萌比男神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:38

    If you don't care about portability, you can use _getch() in VC.

    #include 
    #include 
    #include 
    
    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 is that you use NCurse which is available in *nix systems also.

提交回复
热议问题