How to avoid using Backspace character with push_back?
I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:
string password2 = "";
cout << "PASSWORD: ";
ch = _getch();
while(ch != 13) //character 13 is enter
{
password2.push_back(ch);
cout << '*';
ch = _getch();
}
And also, I try to use pop_back(); but it doesn't work either. Can anybody help me please?
Are you trying to make it so that when the user presses Backspace, it deletes the last character in the string as well the * character that was printed?
Basically, you check if the user entered '\b', and if so, then overwrite the last * with a space and move the cursor back one spot.
If password2.pop_back(); doesn't work for you, I would recommend updating your compiler.
(Or use password2.erase(password2.end() - 1);.)
I whipped this up really quickly, so this is probably bad code (well, at least it doesn't use <conio.h>), but it does seem to work (as long as you're running Windows, and you stick to ASCII characters only):
Enter your password: ****************
Okay, your password was: Password123!@#$%
Just to make sure everything still works, enter something: test
Okay, you entered: test