如何在C ++中使用cin隐藏用户输入? [英] How do I hide user input with cin in C++?
问题描述
可能重复:
从std :: cin
Possible Duplicate:
Read a password from std::cin
我正在尝试制作一个简单的密码程序,以使我熟悉C ++,但是我遇到了一些问题.在此代码中,我要求用户输入他们选择的密码,然后他们输入该密码.我要编写的代码是隐藏输入(不用* s代替),但是仍然显示光标以及输入密码之前,之后的文本,例如:
I'm trying to make a simple password program so I can get familiar with C++, but I'm having a bit of a problem. In this code, I ask the user for a password they choose, and then they enter it. What I want to code to do is hide the input (not replace it with *s), but still show the cursor, and the text above, before, and after the password is entered, like this:
Please enter password: [don't show input]
Please re-enter password: [don't show input]
我该怎么做?我正在使用Linux,因此将无法使用任何Windows库(windows.h等).
How can I do this? I'm using Linux, so I won't be able to use any windows libraries (windows.h, etc).
推荐答案
您不能直接使用cin执行此操作.您必须降低".尝试调用以下功能:
You cannot do this directly using cin. You have to go "lower". Try calling these functions:
#include <termios.h>
...
void HideStdinKeystrokes()
{
termios tty;
tcgetattr(STDIN_FILENO, &tty);
/* we want to disable echo */
tty.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
void ShowStdinKeystrokes()
{
termios tty;
tcgetattr(STDIN_FILENO, &tty);
/* we want to reenable echo */
tty.c_lflag |= ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &tty);
}
这篇关于如何在C ++中使用cin隐藏用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!