Reading a password from std::cin(从 std::cin 读取密码)
问题描述
我需要从标准输入中读取密码并希望 std::cin
不回显用户输入的字符...
I need to read a password from standard input and wanted std::cin
not to echo the characters typed by the user...
如何禁用 std::cin 的回声?
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 );
我正在寻找一种与操作系统无关的方式来做到这一点.此处 可以在 Windows 和 *nix 中执行此操作.
I'm looking for a OS agnostic way to do this. Here there are ways to do this in both Windows and *nix.
推荐答案
@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:
#ifdef WIN32
#include <windows.h>
#else
#include <termios.h>
#include <unistd.h>
#endif
void SetStdinEcho(bool enable = true)
{
#ifdef WIN32
HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);
DWORD mode;
GetConsoleMode(hStdin, &mode);
if( !enable )
mode &= ~ENABLE_ECHO_INPUT;
else
mode |= ENABLE_ECHO_INPUT;
SetConsoleMode(hStdin, mode );
#else
struct termios tty;
tcgetattr(STDIN_FILENO, &tty);
if( !enable )
tty.c_lflag &= ~ECHO;
else
tty.c_lflag |= ECHO;
(void) tcsetattr(STDIN_FILENO, TCSANOW, &tty);
#endif
}
示例用法:
#include <iostream>
#include <string>
int main()
{
SetStdinEcho(false);
std::string password;
std::cin >> password;
SetStdinEcho(true);
std::cout << password << std::endl;
return 0;
}
这篇关于从 std::cin 读取密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 std::cin 读取密码


- 如何提取 __VA_ARGS__? 2022-01-01
- 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
- DoEvents 等效于 C++? 2021-01-01
- GDB 不显示函数名 2022-01-01
- OpenGL 对象的 RAII 包装器 2021-01-01
- 将函数的返回值分配给引用 C++? 2022-01-01
- 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
- 哪个更快:if (bool) 或 if(int)? 2022-01-01
- 将 hdc 内容复制到位图 2022-09-04
- XML Schema 到 C++ 类 2022-01-01