password masking in c++

半世苍凉 提交于 2020-01-07 03:04:53

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/35298610/password-masking-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!