密码屏蔽(输入显示为********)

Password masking (input displayed as ********)

本文关键字:显示 输入 屏蔽 密码      更新时间:2023-10-16

>我编写了一个程序,可以从用户那里获取输入以输入他的用户名和密码,但我想要的是当用户输入他的密码时,它显示为*****而不是英语,就像我们在Gmail中输入密码一样。

我在互联网上进行了研究,并设法编写了这个程序,但我无法在密码中输入任何内容。我也不完全理解我写的代码。

class user
{
private:
   string name;
   string pass;
public:
                void mask()
{
        char c;
        for(int i=0;i<100;i++)
        {
                c=getch();
                if(c=='r')
                        break;
                std::cout<<"*";
                pass=pass+c;
        }
}
        void getdata()
        {
                int flag=0;
                do
                {
                cout<<"Enter username: ";std::getline(std::cin,name);
                cout<<endl;
                cout<<"Enter password: ";mask();
                cout<<endl;
                 if((name=="myname")&&(pass=="tiger"))
                        {
                                cout<<"nnLogin successful"<<endl;
                                flag=1;
                        }
                else
                        cout<<"nnInvalid username or passwordnnHint:Your username and password is myname and tiger"<<endl<<endl;
        }while(flag==0);
        }
};
问题已经

问了,不管这是我的实现 它只接受有效的输入(数字和字母可以很容易地改变(,并且支持退格

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
    string password = "";
    while (!GetAsyncKeyState(VK_RETURN) & 1)
    {
        for (int i = 0x30; i < 0x5A; i++)
        {
            if (GetAsyncKeyState(i) & 1)
            {
                if (i >= 0x41 && i <= 0x5A && ((GetKeyState(VK_CAPITAL) & 1) == 0 || GetAsyncKeyState(VK_SHIFT) & 1))
                    password += ((char)i + 32);
                else
                    password += (char)i;
                cout << "*";
                Sleep(50);
            }
            else if (GetAsyncKeyState(VK_BACK) & 1)
            {
                password.erase(password.size() - 1);
                system("cls");
                for (int i = 0; i < password.size(); i++)
                {
                    cout << '*';
                }
                Sleep(50);
            }
        }
    }
    cout << password;
    Sleep(10000);
}