在input时显示*(隐藏/屏蔽input)

我正在获取密码作为input的过程。 我已经通过各种示例,但他们要么使用循环或SETCONSOLE方法。 两者都有问题。 实现while循环打印1 *之前,我甚至input一个字符。 另一种方法使用回声来隐藏字符,而我打字,而我想打印。 我将不胜感激帮助我用*使用SETCONSOLE方法掩盖我的input。 我会非常感激。 代码附上!

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

}

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

它可以扩展到阻止空格,标签等

另请参阅代码中的注释…

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

你可能想要使用getch()#include <conio.h> )来读取一个字符,而不会被回显到屏幕上。 然后当你确认你想要接受的角色时,你可以在正确的位置打印一个*