代码中的注释可以解释这一点。退格字符只向后移动,不擦除输出,所以我需要用' '覆盖它们来删除它们。
#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;发布于 2021-02-27 18:28:28
关于您的程序的效率,请记住,过早的优化是所有邪恶的根源。看一下你的程序,我可以看出你的程序将是IO绑定的--这意味着计算机将花费更长的时间等待用户输入数据,而不是实际执行你的程序。此外,像std::cout这样处理输出的函数包括不可避免的缓慢的系统调用,这将比您的算法花费更多时间。因此,这里不应考虑性能!)
关于您的程序效率,我要说的唯一一件事是const string PASSWORD = "PASSWORD";,它将使用不必要的复制和堆分配。最好保持字符串的原始类型如下:
const auto PASSWORD = "PASSWORD"; (在这里auto (假设为c++11)为您推导了类型,但是如果您想知道的话,真正的字符串类型是const char* )
以下是我将在您的代码上提出的样式/可读性要点。
using namespace std --这会导致命名冲突和所有可怕的错误。最好每次都使用std::。PASSWORD作为一个static const变量放在main中,这将限制PASSWORD的可见性。c更好的变量名。main函数更加整洁。就这样!做得好,我要说的是,一般来说,这是写得很好的,可读的c++代码。
https://codereview.stackexchange.com/questions/256513
复制相似问题