Reputation: 763
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.
Upvotes: 0
Views: 3608
Reputation: 449
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.
Upvotes: 1