The comments in the code kind of explain it. Backspace characters only move cursor back and don't erase output so I need to overwrite them with ' '
to delete them.
#include <iostream>
#include <string>
using namespace std;
const string PASSWORD = "PASSWORD";
int main(int argc, char** argv) {
string userkey = "";
char c;
int keystrokes = 0;
cout<<"Enter passkey: ";
while(true){
if(_kbhit()){
c=_getche();
if(c=='\r'){//check if user hit enter, _getche() records enter as \r
cout<<'\n';
break;
}
else if(c =='\b'){//check if user typed backslash, overwrite character there
cout<<' ';
if(keystrokes==1){ //makes sure userkey is cleared
userkey = "";
keystrokes--;
cout<<'\b';
}
else if(keystrokes!=0){
userkey = userkey.substr(0,userkey.length()-1);//cuts out last char of userkey
keystrokes--;
cout<<'\b';
}
}
else if (c!='\b'){
cout<<"\b*";//replaces enter char with'*'
keystrokes++;
userkey+=c;
}
}
}
//cout<<userkey;
if (userkey!=PASSWORD)
return 0;
_kbhit()
and_getche()
, since you don't present them here, and don't have any includes for them. But note that identifiers beginning with_
are reserved for the implementation, so you should be using more portable names. \$\endgroup\$