Replacement to getch based code block in cpp

只愿长相守 提交于 2021-01-28 19:52:42

问题


I stumbled upon a code from 2016 written in the Turbo C++ IDE in windows It was to accept passwords

char pass;
    for (length = 0;;)
    {
        pass=getch();
        if (pass == 13)
        {
            break;
        }
        if ((pass >= 'A' && pass <= 'Z') || (pass >= 'a' && pass <= 'z') || (pass >= '0' && pass <= '9') || (pass == '!' || '@' || '#' || '$' || '%' || '^' || '&' || '*' || '(' || ')'))
        {
            str[length] = pass;
            ++length;
            cout << "#";
        }
    }

is there any replacement for this without the getch method for linux to show output like this ******** ? I tried scanf but that didnt work cause it took the whole input first and gave the output later


回答1:


There is no standard replacement in C++.

Linux (and similar systems such as BSD), there is a legacy function getpass whose use is not recommended. I mention it because the documentation of that function in glibc suggests following:

This precise set of operations may not suit all possible situations. In this case, it is recommended that users write their own getpass substitute. For instance, a very simple substitute is as follows:

#include <termios.h>
#include <stdio.h>

ssize_t
my_getpass (char **lineptr, size_t *n, FILE *stream)
{
  struct termios old, new;
  int nread;

  /* Turn echoing off and fail if we can’t. */
  if (tcgetattr (fileno (stream), &old) != 0)
    return -1;
  new = old;
  new.c_lflag &= ~ECHO;
  if (tcsetattr (fileno (stream), TCSAFLUSH, &new) != 0)
    return -1;

  /* Read the passphrase */
  nread = getline (lineptr, n, stream);

  /* Restore terminal. */
  (void) tcsetattr (fileno (stream), TCSAFLUSH, &old);

  return nread;
}

Note that the example is written in C, and is not valid C++. Small changes are required, in particular there is a C++ keyword new being used as a variable name. Simply rename it to something else.

Also note that the behaviour is to not echo at all, rather than echo *. This is conventional in POSIX systems, and safer because the it does not reveal the length of the passphrase.



来源:https://stackoverflow.com/questions/63038561/replacement-to-getch-based-code-block-in-cpp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!