C ++ masking passwords

I am writing a code to enter a password. Below is my code ... the program works well, but the problem is other keys besides numeric and alphabetic characters, which are also read, for example, delete, insert, etc. Can I find out how I can avoid this? TQ ...

string pw="";
char c=' ';

while(c != 13) //Loop until 'Enter' is pressed
{
    c = _getch();
    if(c==13)
        break;

    if(c==8)
    {
        if(pw.size()!=0)   //delete only if there is input 
        {
            cout<<"\b \b";
            pw.erase(pw.size()-1);
        }
    }

    if((c>47&&c<58)||(c>64&&c<91)||(c>96&&c<123))  //ASCii code for integer and alphabet
    {
        pw += c;
        cout << "*";
    }
}
+3
source share
2 answers

Use filter isalnum()for alphanumeric or isalpha()alphabetic only.

In addition, you check twice c == 13, the next one will be sufficient.

while(1){
  //
  if(c == 13)
    break;
  //
}

if( isalnum(c) ){
  // 'c' is acceptable
}

Some statement is not executed at run time, which causes this error.

+7
source

, GNU getpass.

+1

Source: https://habr.com/ru/post/1738645/


All Articles