0

My professor is asking me to make a program that asks for email and password that while the user is typing its password the characters will be changed into *, My problem is whenever I press backspace it continues to print * and not deleting it. Please help me how this program will delete the previous character and not add * when I press backspace. Thanks You can also add a tip on how I can improve my programming

CODE

Here is the code that I'm working with

#include <iostream>
#include <string>
#include <conio.h>
using namespace std;

int main() 
{
    string pass = "";
    char password;
    string email;
    string name;
    name = "Mon Alvin Rafael";
    cout << " Enter Email: ";
    cin >> em;
    cout << " Enter Password: \b";
    password = _getch();
    while (ch != 13) {
        //character 13 is enter
        pass.push_back(password);
        cout << '*';
        ch = _getch();
    }
    if (pass == "password1234" && email == "email1234")
    {
        cout << "\n Welcome " << name << endl;
        return main();
    }
    else 
    {
        cout << "\n Invalid Password or Email" << endl;
        return main();
    }
}
  • @MichaelChourdakis How would you hide the password on screen using streams? – Yksisarvinen Feb 02 '22 at 14:18
  • 1
    You can check if `ch == '\b'` to detect backspace and then print `'\b'` to terminal, which should delete one `*`. (`'\b'` just means `8` which is backspace code. Similarly you can change the `while (ch != 13)` to `while (ch != '\n')`.) – Piotr Siupa Feb 02 '22 at 14:22
  • As noted by @NO_NAME, decimal value 8 for backspace - ASCII table is your friend here. – ChrisBD Feb 02 '22 at 14:24
  • Don't do `return main();`. Calling `main` is illegal in C++. – Piotr Siupa Feb 02 '22 at 14:24
  • 1
    Related to [hide-user-input-on-password-prompt](https://stackoverflow.com/questions/6899025/hide-user-input-on-password-prompt) – Jarod42 Feb 02 '22 at 14:27

1 Answers1

1

You can check if the user presses the backspace (character code 8) and if the do print the backspace character '\b' to move the cursor back by one, followed by ' ' to overwrite the '*' and then another backspace character the move the cursor back again. Of course making sure to also delete the last character from the password string.

string pass = "";
char ch;
string email;
string name;
name = "Mon Alvin Rafael";
cout << " Enter Email: ";
cin >> email;
cout << " Enter Password: \b";
ch = _getch();
while (ch != 13) {
    if (ch == 8) {
        // backspace was pressed
        if (pass.length()) {
            cout << "\b \b";
            pass.pop_back();
        }
        ch = _getch();
        continue;
    }
    //character 13 is enter
    pass.push_back(ch);
    cout << '*';
    ch = _getch();
}
rdtsc
  • 303
  • 2
  • 10