Possible Duplicate:
Read a password from std::cin
我不能正常使用控制台,所以我的问题可能很容易回答或不可能做到。
是否可以将cin
和cout
“解耦”,这样我在控制台中输入的内容就不会再次直接出现在其中了?
我需要这个来让用户输入密码,而我和用户通常都不希望他的密码以 plaintext
出现在屏幕上。
我尝试在 stringstream
上使用 std::cin.tie
,但我输入的所有内容仍然反射(reflect)在控制台中。
最佳答案
来自 How to Hide Text :
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
关于c++ - 在密码提示中隐藏用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6899025/