3

i'm writing a code to receive password input. Below is my code... the program run well but the problem is other keys beside than numerical and alphabet characters also being read, for example delete, insert, and etc. can i know how can i avoid it? 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 << "*";
    }
}
Michael Kristofik
  • 34,290
  • 15
  • 75
  • 125
blaxc
  • 73
  • 2
  • 5
  • possible duplicate of [Read a password from std::cin](http://stackoverflow.com/questions/1413445/read-a-password-from-stdcin) – jww Oct 06 '14 at 04:32

2 Answers2

7

Filter using isalnum() for alpha-numeric or isalpha() for only alphabets.

Also, you are checking c == 13 twice, following will suffice.

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

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

Some assertion is failing during execution which throws that error.

N 1.1
  • 12,418
  • 6
  • 43
  • 61
  • i had changed it to: if(isalnum(c)!=0||isalpha(c)!=0) But... now if i press key like delete or insert, the program crash and pop up a window (Debug Assertion Failed). how can i handle the assertion? tq for ur reply... – blaxc Mar 26 '10 at 11:46
  • no i din assert anything... the program will crash and said assertion failed when i press others key.. i now changed my code to if(isalnumc(c) || isalpha(c)) it's only work well if i enter numerical or alphabet... – blaxc Mar 26 '10 at 12:30
  • if i use getchar(), the password that user key in will be displayed before the '*' being displayed.. but that 1 can solve the assertion problem.. – blaxc Mar 26 '10 at 12:49
  • It's also important to mention that it is undefined behaviour to check ranges of chars rather than using is*(). – L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳ May 14 '10 at 23:10
  • You really do NOT want to use isalnum checks for passwords. Better check for !isctrl so people can use whitespace in their passwords. – ThiefMaster Nov 04 '10 at 00:22
2

If you have access to it, you are much better off using the GNU getpass function.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365