简体   繁体   中英

password masking in c++

I want to implement a login form in c++, so I wrote a function as follows:

string setPass(bool show_asterisk = true)
{
    const char BACKSPACE = 8;//ASCII code for BACKSPACE Key
    const char ENTER = 13;//ASCII code for ENTER Key
    string pass = " ";//initialize string
    char c = ' ';//initialize character 

    while ((c = _getch()) != ENTER)
    {
        if (c == BACKSPACE)
        {
            if (pass.length() != 0)
            {
                if (show_asterisk)
                   cout << "\b \b";
                pass.resize(pass.length() - 1); //resize the length of pass 
            }
        }
        else if (c == 0 || c == 224)//when player press esc key
        {
            _getch();
            continue;
        }
        else
        {
            pass.push_back(c);
            cout << '*';
        }
    }
    cout << endl;
    return pass;
}

Here is the code that executes the function:

cout << "==================" << endl;
cout << "      login       " << endl;
cout << "  ID:";
cin >> id;
cout << "  Password:";
cin >> pwd;
pwd = setPass();

I compiled this code but it seems like the function didn't work, because the password is not being masked. Here's an image showing what happens:

在此处输入图片说明

I tried to fix the problem but I can't figure it out.

I don't know how do you compare the passwords. However, you are initializing the pass string inside the setPass() function with = " "; . Note that the function always returns the password beggining with the useless empty space character.

Enter password: ****
Output: " asdf"

Secondly, I don't see any purpose of cin in this part:

cin >> pwd;
pwd = setPass();

I fixed these things I mentioned here, compiled the code, and it works as you wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM