I'm using a piece of code from cplusplus, and i can't get it why this code just skips the input part for password and just jumps right to the input for EMAIL.
//function to mask the input for password
string getpass(const char *prompt, bool show_asterisk=true)
{
const char BACKSPACE=127;
const char RETURN=10;
string password;
unsigned char ch=0;
//cout <<prompt<<endl;
while((ch=getch())!=RETURN)
{
if(ch==BACKSPACE)
{
if(password.length()!=0)
{
if(show_asterisk)
cout <<"\b \b";
password.resize(password.length()-1);
}
}
else
{
password+=ch;
if(show_asterisk)
cout <<'*';
}
}
cout <<endl;
return password;
}
And here I'm calling this function:
void AgendaUI::userRegister(void)
{
string name, password, email, phone;
//cout << "\n[register] [username] [password] [email] [phone]" << endl;
cout << "\n[regist]";
cout << "\n[username] ";
cin >> name;
cout << "[password] ";
password = getpass("Enter the password",true);
cout << "\n[email] ";
cin >> email;
cout << "[phone] ";
cin >> phone;
}
Because when your user entered the username, they also entered the Enter character (that's how their terminal knew to submit the line). This character was not read by cin >> name
and is still there in the buffer. Then, getpass
reads it as the first character, and immediately stops.
Notice how your code is not the same as the article's code, which does not ask for a username, and shows a getpass
that is rather fragile (e.g. it breaks when simply adding the basic code that you added, and seems to rely on the termios hacks that you quietly removed). In general try not to learn C++ from articles on websites. Learn it from a good book instead!
You can fix this by adding cin.ignore(256, '\n')
after cin >> name
, though frankly that's a bit of a hack and it would arguably be better to extract the username using std::getline
instead.