我试图掩盖用户输入并将其存储在变量中。当我按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
}
在许多系统(包括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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句