0

So I am creating a simple password program that asks you for an input but masks it with asterisks (*). The code I have works, but when I backspace the string returned is like I had never backspaced.

What I would Type:

12345

I would hit the backspace twice, and the string would look like this:

123

But when I hit enter, it returns this:

1234

Here is the code that I have.

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

string Encrypted_Text(int a) {   //Code for the password masker
    string Pwd = " ";            //Creates password variable.
    char Temp;                   //Temporary variable that stores current keystroke.
    int Length = 0;              //Controls how long that password is.
    for (;;) {                   //Loops until the password is above the min. amount.
        Temp = _getch();         //Gets keystroke.

        while (Temp != 13) {     //Loops until enter is hit.
            Length++;            //Increases length of password.
            Pwd.push_back(Temp); //Adds newly typed key on to the string.
            cout << "*";
            Temp = _getch();     // VV This is were the error is VV
            if (Temp == 8) {     // detects when you hit the backspace key.
                Pwd.pop_back;    //removes the last character on string.
                cout << "\b ";   //Deletes the last character on console.
                Length--;        //decreases the length of the string.
            }
        }
        if (Length < a) {        //Tests to see if the password is long enough.
            cout << "\nInput Is To Short.\n";
            Pwd = "";
            Temp = 0;
            Length = 0;
        }
        else {
            break;
        }
    }
    return Pwd; //Returns password.
}

And in my main function i have this:

string Test = Encrypted_Text(5);
cout << "you entered : " << Test;
Dosisod
  • 307
  • 2
  • 15

1 Answers1

1

In your code you push_back whatever character you get. Only after that you remove a character if it is a backspace. This is why it doesn't work.

You need to first check for special characters and only if it is not one of those you add the character.

Also there is no need to have the Length variable since std::string knows its length and you can get it from there.

Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74