【问题标题】:Taking string input without displaying its actual content (for PASSWORDS)接受字符串输入而不显示其实际内容(对于密码)
【发布时间】:2020-11-02 05:31:16
【问题描述】:

如何创建一个不显示您输入的内容而是显示另一个字符的输入函数? 例如,假设您输入了“hello”,它什么也不显示或显示“*****”。具有适当的退格功能。 提前致谢

【问题讨论】:

标签: c++


【解决方案1】:

编辑:看起来您已经知道自己问题的答案了?我将把它留在这里,以防其他人发现它有用......

¯\_(ツ)_/¯

我假设您希望在控制台应用程序中执行此操作,并且您可能使用的是 Windows。如果是这样,我从https://www.cplusplus.com/articles/E6vU7k9E/ 在线找到了这个解决方案——也许可以试试这个方法。该链接也有其他平台的方法。

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;


string getpass(const char *prompt, bool show_asterisk=true)
{
  const char BACKSPACE=8;
  const char RETURN=13;

  string password;
  unsigned char ch=0;

  cout <<prompt<<endl;

  DWORD con_mode;
  DWORD dwRead;

  HANDLE hIn=GetStdHandle(STD_INPUT_HANDLE);

  GetConsoleMode( hIn, &con_mode );
  SetConsoleMode( hIn, con_mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT) );

  while(ReadConsoleA( hIn, &ch, 1, &dwRead, NULL) && ch !=RETURN)
    {
       if(ch==BACKSPACE)
         {
            if(password.length()!=0)
              {
                 if(show_asterisk)
                     cout <<"\b \b";
                 password.resize(password.length()-1);
              }
         }
       else
         {
             password+=ch;
             if(show_asterisk)
                 cout <<'*';
         }
    }
  cout <<endl;
  return password;
}

【讨论】:

    【解决方案2】:

    对于窗户, 使用

    string passwdIO()
    {
        HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); 
        DWORD mode = 0;
        GetConsoleMode(hStdin, &mode);
        SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT));
        string input;
        getline(cin, input);
        SetConsoleMode(hStdin, mode);
        return input;
    }
    

    这是执行此操作的正常方法。该函数返回不显示在屏幕上的字符串。

    但我们可以使用 iostream 和

    string encPasswd(const char _dsp){
        string _final = "";
        char chr_ipt;
        while(true){
            chr_ipt = getch();
            if (chr_ipt < 32 && chr_ipt != 8)
                return _final;
                if(chr_ipt == 8 && _final.length() != 0){
                _final.pop_back();
                cout << "\b \b";
                continue;
            }
            if(chr_ipt == 8 && _final.length() == 0) continue; 
            // without this^ program will crash at some point
    
            _final.push_back(chr_ipt);
            cout << _dsp;
        }
    }
    

    此函数在接受输入时返回字符串,但显示另一个字符 (_dsp)

    【讨论】:

    • 希望第二个非常简单实用。
    【解决方案3】:

    在 C++ 中没有标准的方法来做到这一点。

    不同的操作系统提供不同的 API 来与(虚拟)终端交互。在这个更具体的问题中有一个适用于 Linux 的解决方案:https://stackoverflow.com/a/63038844/2079303

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-28
      • 2010-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-05
      相关资源
      最近更新 更多