我试图屏蔽用户输入并将其存储在一个变量中。但是,当我按enter键时,程序应该从循环中中断,enter键仍然注册为字符:
#inlcude <iostream>
#include <conio.h>
std::cout << "Password: ";
char c;
// Masks the password
while ((c = _getch()))
{
if (c == '\n')
{
break;
}
passwd.push_back(c); // put it onto the back of the password
_putch('*'); // output a '*' character
}
发布于 2020-08-08 13:36:51
在许多系统(包括Windows)中,换行符‘'\n'
’实际上表示两个字符的组合:一个回车(ASCII 13)加上一个行提要(ASCII 10)。
对于"Enter“键(也就是回车返回),请使用'\r'
转义序列:
#include <iostream>
#include <string>
#include <conio.h>
int main()
{
std::string passwd;
std::cout << "Password: ";
char c;
// Masks the password
while ((c = _getch())) {
if (c == '\r') {
break;
}
passwd.push_back(c); // put it onto the back of the password
_putch('*'); // output a '*' character
}
std::cout << std::endl << passwd << std::endl;
return 0;
}
https://stackoverflow.com/questions/63320402
复制相似问题