2016-02-14 14 views
0

所以我创建了一个简单的密码程序,要求输入密码但用星号(*)掩盖。我的代码有效,但是当我退格时,返回的字符串就像我从来没有退后一样。C++密码程序,字符串在退格时不会删除最后一个字符

我将键入的内容:

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; 

回答

1

在你的代码push_back任何字符,你得到的。只有在此之后,您才能删除一个字符,如果它是退格。这就是为什么它不起作用。

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

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

+0

谢谢你的建议。一点点重新安排,我得到的代码工作:D – Dosisod

相关问题