C ++密码程序,字符串在退格时不会删除最后一个字符

C++ Password program, string wont delete last character when backspacing

所以我正在创建一个简单的密码程序,它要求您输入但用星号 (*) 屏蔽它。我的代码有效,但是当我退格时,返回的字符串就像我从未退格过一样。

我要输入的内容:

12345

我会按退格键两次,字符串看起来像这样:

123

但是当我按下回车键时,它 returns 是这样的:

1234

这是我的代码。

#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.
}

在我的主要功能中我有这个:

string Test = Encrypted_Text(5);
cout << "you entered : " << Test;

在您的代码中,您 push_back 无论您获得什么字符。只有在那之后你删除一个字符,如果它是退格键。这就是它不起作用的原因。

您需要先检查特殊字符,只有当它不是特殊字符时才添加字符。

也不需要 Length 变量,因为 std::string 知道它的长度,你可以从那里得到它。