所以我创建了一个简单的密码程序,要求您输入,但用星号(*)掩盖它。我的代码有效,但当我退格时,返回的字符串就像我从未退格过。
我会输入什么:
12345
我会两次击退退格,字符串看起来像这样:
123
但是当我按下回车键时,它会返回:
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;
答案 0 :(得分:1)
在你的代码中push_back
你获得的任何角色。只有在那之后你删除一个字符,如果它是退格。这就是为什么它不起作用。
您需要首先检查特殊字符,并且只有在它不是您添加字符的字符时才需要。
此外,不需要Length
变量,因为std::string
知道它的长度,你可以从那里得到它。