Search code examples
c++linuxg++c++17turbo-c++

Replacement to getch based code block in cpp


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


Solution

  • 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.