在密码提示中隐藏用户输入
可能重复:
从std::cin读取密码
我不能正常使用控制台,所以我的问题可能很容易回答或不可能做到.
I don't work normally with the console, so my question is maybe very easy to answer or impossible to do .
是否可以将cin
和cout
解耦",这样我在控制台中输入的内容就不会再次直接出现在其中了?
Is it possible to "decouple" cin
and cout
, so that what I type into the console doesn't appear directly in it again?
我需要这个来让用户输入密码,而我和用户通常都不希望他的密码以 plaintext
出现在屏幕上.
I need this for letting the user typing a password and neither me nor the user normally wants his password appearing in plaintext
on the screen.
我尝试在 stringstream
上使用 std::cin.tie
,但我输入的所有内容仍然反映在控制台中.
I tried using std::cin.tie
on a stringstream
, but everything I type is still mirrored in the console.
推荐答案
来自如何隐藏文本:
Windows
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;
int main()
{
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode = 0;
GetConsoleMode(hStdin, &mode);
SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main
清理:
SetConsoleMode(hStdin, mode);
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
Linux
#include <iostream>
#include <string>
#include <termios.h>
#include <unistd.h>
using namespace std;
int main()
{
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
string s;
getline(cin, s);
cout << s << endl;
return 0;
}//main
相关文章