我正在使用来自 cplusplus 的一段代码,我不明白为什么这段代码只是跳过密码的输入部分并直接跳转到 EMAIL 的输入部分。
//function to mask the input for password
string getpass(const char *prompt, bool show_asterisk=true)
{
const char BACKSPACE=127;
const char RETURN=10;
string password;
unsigned char ch=0;
//cout <<prompt<<endl;
while((ch=getch())!=RETURN)
{
if(ch==BACKSPACE)
{
if(password.length()!=0)
{
if(show_asterisk)
cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password+=ch;
if(show_asterisk)
cout <<'*';
}
}
cout <<endl;
return password;
}
我在这里调用这个函数:
void AgendaUI::userRegister(void)
{
string name, password, email, phone;
//cout << "\n[register] [username] [password] [email] [phone]" << endl;
cout << "\n[regist]";
cout << "\n[username] ";
cin >> name;
cout << "[password] ";
password = getpass("Enter the password",true);
cout << "\n[email] ";
cin >> email;
cout << "[phone] ";
cin >> phone;
}
最佳答案
因为当您的用户输入用户名时,他们还输入了 Enter 字符(这就是他们的终端知道提交该行的方式)。此字符未被 cin >> name
读取,并且仍存在于缓冲区中。然后,getpass
将其作为第一个字符读取,并立即停止。
请注意您的代码与文章的代码有何不同,文章的代码不要求用户名,并且显示了一个相当脆弱的 getpass
(例如,当简单地添加基本代码时它会中断您添加的,并且似乎依赖于您悄悄删除的 termios hack)。一般来说,尽量不要从网站上的文章中学习 C++。向a good book学习相反!
您可以通过 adding cin.ignore(256, '\n')
after cin >> name
解决这个问题,虽然坦率地说这有点 hack,但可以说使用 std::getline
提取用户名会更好。
关于c++ - 输入缓冲和屏蔽密码输入 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53561342/