从 std::cin 读取密码
我需要从标准输入读取密码,并且希望 std::cin 不回显用户键入的字符...
如何禁用 std::cin 的回显?
这是我当前正在使用的代码:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
我正在寻找一种与操作系统无关的方法来执行此操作。 这里有一些方法可以在 Windows 和 *nix 中执行此操作。
I need to read a password from standard input and wanted std::cin
not to echo the characters typed by the user...
How can I disable the echo from std::cin?
here is the code that I'm currently using:
string passwd;
cout << "Enter the password: ";
getline( cin, passwd );
I'm looking for a OS agnostic way to do this.
Here there are ways to do this in both Windows and *nix.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
@wrang-wrang 答案非常好,但没有满足我的需求,这就是我的最终代码(基于 this) 看起来像:
示例用法:
@wrang-wrang answer was really good, but did not fulfill my needs, this is what my final code (which was based on this) look like:
Sample usage:
标准中没有任何内容。
在 unix 中,您可以根据终端类型编写一些魔术字节。
使用 getpasswd(如果可用)。
您可以使用 system() /usr/bin/stty -echo 来禁用 echo,并使用
/usr/bin/stty echo 来启用它(同样,在 unix 上)。
这个人解释了如何在不使用“的情况下做到这一点” stty”;我自己没有尝试过。
There's nothing in the standard for this.
In unix, you could write some magic bytes depending on the terminal type.
Use getpasswd if it's available.
You can system()
/usr/bin/stty -echo
to disable echo, and/usr/bin/stty echo
to enable it (again, on unix).This guy explains how to do it without using "stty"; I didn't try it myself.
如果你不关心可移植性,可以在
VC
中使用_getch()
。还有用于
宽字符
的getwch()
。我的建议是您使用NCurse
,它可以在 < code>*nix 系统也是如此。If you don't care about portability, you can use
_getch()
inVC
.There is also
getwch()
forwide characters
. My advice is that you useNCurse
which is available in*nix
systems also.只知道我有什么,你可以逐个字符地读取密码,然后打印退格键(“\b”),也许还有“*”。
Only idea what i have, you could read password char by char, and after it just print backspace ("\b") and maybe '*'.