参考
教程
https://terminalroot.com/how-to-hide-input-via-cli-with-cpp/?ref=morioh.com&utm_source=morioh.com
man信息#include <termios.h>
https://pubs.opengroup.org/onlinepubs/7908799/xsh/termios.h.html
举例
#include <iostream>
#include <termios.h>
#include <unistd.h>
/* https://man7.org/linux/man-pages/man0/termios.h.0p.html
The <termios.h> header shall contain the definitions used by the
terminal I/O interfaces (see Chapter 11, General Terminal
Interface for the structures and names defined).*/
using namespace std;
int main()
{
string pswd;
string stdpswd = "1234";
// set attribute of stdin: hide input pswd
termios oldt;
tcgetattr(STDIN_FILENO, &oldt);
termios newt = oldt;
newt.c_lflag &= ~ECHO; // ECHO bit: Enables echo. If this flag is set, characters are echoed as they are received.
tcsetattr(STDIN_FILENO, TCSANOW, &newt); // TCSANOW: Change attributes immediately.
while (1)
{
cout << "Enter password: ";
char c;
while ((c = getchar()) != EOF && c != '\n' && c != '\r')
{
pswd.push_back(c);
}
if (feof(stdin))
{
cout << "End of stdin!" << endl;
return 0;
}
cout << endl;
if (pswd == stdpswd)
{
break;
}
pswd.clear();
cout << "Wrong password." << endl;
}
// recover attribute
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
cout << pswd << endl;
return 0;
}