我无法正常使用控制台,所以我的问题可能很容易回答或无法做到。
是否可以“解耦”cin
和cout
,以便我在控制台中输入的内容不会直接出现在其中?
我需要这个让用户输入密码,我和用户通常都不希望他的密码显示在屏幕上的plaintext
。
我尝试在std::cin.tie
上使用stringstream
,但我输入的所有内容仍在镜像中镜像。
答案 0 :(得分:36)
<强>窗强>
#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
答案 1 :(得分:5)
你真的在问两个无关的问题
调用cin.tie( NULL )
解耦std::cin
和std::cout
完全。但它不会影响较低级别的任何事情。在最低级别,至少在Windows和Unix下,std::cin
和std::cout
都连接到系统级别的同一设备,并且它是该设备(Unix下为/dev/tty
)这是回声;您甚至可以将标准重定向到文件,控制台仍然会回显输入。
如何关闭此回音取决于系统;最简单的解决方案可能是使用某种第三方库,如curses或ncurses,它提供更高级别的接口,并隐藏所有系统依赖性。
答案 2 :(得分:3)
使用getch()
获取输入而不是使用cin
,因此输入将不会显示(引用wiki):
int getch(void)直接从控制台读取一个字符 缓冲区,没有回声。
这真的是C,而不是C ++,但它可能适合你。
此外,这里还有another link。