替换为cpp中基于getch的代码块 [英] Replacement to getch based code block in cpp

查看:87
本文介绍了替换为cpp中基于getch的代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然在Windows中用Turbo C ++ IDE编写了2016年的代码那是接受密码

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 << "#";
        }
    }

如果没有 linux 的getch方法来显示类似********的输出,是否可以替代此方法?我尝试了scanf,但没有成功,因为它首先获取了整个输入,后来又给出了输出

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

推荐答案

C ++中没有标准替代品.

There is no standard replacement in C++.

在Linux(以及类似的系统,例如BSD)上,有一个遗留函数 getpass ,建议不要使用它.我之所以提及它,是因为glibc中该函数的文档建议以下:

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:

这组精确的操作可能并不适合所有可能的情况.在这种情况下,建议用户编写自己的getpass替代项.例如,一个非常简单的替代方法如下:

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;
}

请注意,该示例是用C编写的,并且不是有效的C ++.需要进行一些小的更改,尤其是将C ++关键字 new 用作变量名.只需将其重命名为其他名称即可.

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.

还请注意,该行为是完全不回显,而不是回显 * .这在POSIX系统中是常规的,并且更安全,因为它不会显示密码短语的长度.

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.

这篇关于替换为cpp中基于getch的代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆