Enter Password in C

后端 未结 5 1796
梦毁少年i
梦毁少年i 2020-12-17 20:17

I am aware that it is not possible to echo the * while you type in standard ANSI C. But is there a way to display nothing while someone is typing their password in the conso

5条回答
  •  太阳男子
    2020-12-17 20:47

    *This is not ANSI C (Thanks Billy) sample

    You can detect keypress with _kbhit(), then get the value using _getch(). Both function will not echo the content on screen.

    #include           //For keyboard events
    #include           //Include this or iostream
    #include            
    int main()
    {
        bool bContinue = true;
        char szBuffer[255] = {0};
        unsigned int nbufIndex = 0;
        while (bContinue)
        {
            if (_kbhit())
            {
                szBuffer[nbufIndex] = _getch();
                if (szBuffer[nbufIndex] == 0xD)
                {
                    bContinue = false;
                }
                else
                {
                    ++nbufIndex;
                    printf("*");
                }
            }
        }
        printf("\n%s\n", szBuffer);
        return 0;
    }
    

提交回复
热议问题