I am in the process of getting password as input. I have gone through various examples but they either used while loop or SETCONSOLE method. Both had issues. Implementing while loop printed 1 * before I even entered a char. The other method used echo to HIDE the characters while I typed whereas I want to be printed. I would appreciate helping me masking my input with a * using SETCONSOLE method. I would be greatly obliged. The code's attached !
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;
}
}
Here a simple example using getch
. YES it c method, not c++, but it is very efficient.
It can be extended to block spaces, tabs, etc.
Also see the comments in the code...
#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;
}