【问题标题】:Show * while I input (Hide/mask input)在我输入时显示 *(隐藏/屏蔽输入)
【发布时间】:2015-06-30 20:21:28
【问题描述】:

我正在获取密码作为输入。 我已经浏览了各种示例,但它们要么使用了 while 循环,要么使用了 SETCONSOLE 方法。两者都有问题。 在我输入一个字符之前实现 while 循环打印 1 *。另一种方法使用 echo HIDE 在我键入时要打印的字符。我会很感激帮助我使用 SETCONSOLE 方法用 * 掩盖我的输入。我将不胜感激。附上代码!

 void signup(){
    gotoxy(10, 10);
    string n, p1,p2;
     cout << "Enter your username: " << endl; // TEST if username already       exists
gotoxy(31, 10);
cin >> n;
lp:
gotoxy(10, 11);
cout << "Enter your password: " << endl; // TEST if username already exists
gotoxy(31, 11);

getline(cin, p1);
system("cls");
gotoxy(10, 10);
cout << "Re-Enter your password to confirm: " << endl; // TEST if username already exists
gotoxy(45, 10);
getline(cin, p2);



if (p2!=p1)
{
    system("cls");
    gotoxy(10, 10);
    cout << "Passwords donot match! Please enter again!";
        goto lp;
}

}

【问题讨论】:

  • 请指定您的目标操作系统,并提供您已经尝试过的短代码 sn-p。
  • 什么是 SETCONSOLE 方法?
  • @Raw N DWORD 模式; HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(hConIn, &mode);模式=开? (模式 | ENABLE_ECHO_INPUT ) : (模式 & ~(ENABLE_ECHO_INPUT)); SetConsoleMode( hConIn, mode );

标签: c++ windows masking


【解决方案1】:

这里是一个使用getch 的简单示例。是的,它是 c 方法,而不是 c++,但它非常有效。

可以扩展成块空格、制表符等

另见代码中的 cmets...

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


int main(){ 
    string res;
    char c;
    cout<<"enter password:";
    do{
        c = getch();
        switch(c){
        case 0://special keys. like: arrows, f1-12 etc.
            getch();//just ignore also the next character.
            break;
        case 13://enter
            cout<<endl;
            break;
        case 8://backspace
            if(res.length()>0){
                res.erase(res.end()-1); //remove last character from string
                cout<<c<<' '<<c;//go back, write space over the character and back again.
            }
            break;
        default://regular ascii
            res += c;//add to string
            cout<<'*';//print `*`
            break;
        }
    }while(c!=13);
    //print result:
    cout<<res<<endl;
    return 0;  
}

【讨论】:

  • 虽然如果密码不匹配,我必须在循环之前使用 clear() 清除字符串,但它确实解决了问题。谢谢:)
  • 虽然解释的其他方法也会有帮助:)
  • 它只是简化了密码输入,你可以把它放在一些getpassword方法中,并在每次输入密码时调用它。
【解决方案2】:

您可能希望使用getch() (#include &lt;conio.h&gt;) 来读取字符,而不会将其回显到屏幕上。然后,当您确认它是您想要接受的字符后,您可以在正确的位置打印出*

【讨论】:

    猜你喜欢
    • 2018-04-23
    • 2018-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    相关资源
    最近更新 更多