C ++中的密码屏蔽 [英] password masking in c++

查看:40
本文介绍了C ++中的密码屏蔽的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用c++实现一个登录表单,所以写了一个函数如下:

I want to implement a login form in c++, so I wrote a function as follows:

string setPass(bool show_asterisk = true)
{
    const char BACKSPACE = 8;//ASCII code for BACKSPACE Key
    const char ENTER = 13;//ASCII code for ENTER Key
    string pass = " ";//initialize string
    char c = ' ';//initialize character 

    while ((c = _getch()) != ENTER)
    {
        if (c == BACKSPACE)
        {
            if (pass.length() != 0)
            {
                if (show_asterisk)
                   cout << "\b \b";
                pass.resize(pass.length() - 1); //resize the length of pass 
            }
        }
        else if (c == 0 || c == 224)//when player press esc key
        {
            _getch();
            continue;
        }
        else
        {
            pass.push_back(c);
            cout << '*';
        }
    }
    cout << endl;
    return pass;
}

这是执行函数的代码:

cout << "==================" << endl;
cout << "      login       " << endl;
cout << "  ID:";
cin >> id;
cout << "  Password:";
cin >> pwd;
pwd = setPass();

我编译了这段代码,但似乎该功能不起作用,因为密码没有被屏蔽.这是一张显示发生了什么的图片:

I compiled this code but it seems like the function didn't work, because the password is not being masked. Here's an image showing what happens:

我试图解决这个问题,但我无法解决.

I tried to fix the problem but I can't figure it out.

推荐答案

我不知道你是如何比较密码的.但是,您正在使用 = " "; 初始化 setPass() 函数内的 pass 字符串.请注意,该函数始终返回以无用空格字符开头的密码.

I don't know how do you compare the passwords. However, you are initializing the pass string inside the setPass() function with = " ";. Note that the function always returns the password beggining with the useless empty space character.

Enter password: ****
Output: " asdf"

其次,我在这部分没有看到 cin 的任何目的:

Secondly, I don't see any purpose of cin in this part:

cin >> pwd;
pwd = setPass();

我修复了我在这里提到的这些东西,编译了代码,它可以如你所愿.

I fixed these things I mentioned here, compiled the code, and it works as you wanted.

这篇关于C ++中的密码屏蔽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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