Link to home
Start Free TrialLog in
Avatar of mkandre
mkandreFlag for United States of America

asked on

Fine tuning the password function

Here's a password function i have that does what it's supposed to.

Now to fine tune it I want to incorporate the backspace so that when a backspace character is detected n goes back to n-1 (i.e. previous character)

eg. if i enter "johns" then press backspace i want n to go back to 4 to overwrite the 's'.

/* Accepting Hidden Password */
void password(char buf[])
{
     int n=0;

   do
   {
        buf[n++]=getch();
      if(buf[n-1]!='\r')
           putch('*');
   }
   while(buf[n-1]!='\r');
   buf[n-1]='\0';
}
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

char * getpassword(void)
{
  static char passwd[255];
  int i;

  printf("password: ");

  for (i = 0; i < 254;) {
    int ch = getch();
    /* CR or NL terminates input */
    if ((ch == '\n') || (ch == '\r')) {
      break;
    }
    /* Backspace or Delete backs up */
    if ((ch == '\b') || (ch == '\377')) {
      if (i > 0) i--;
      else putch('\a');
    } else {
      passwd[i++] = (char)ch;
      putch('*');
    }
  }
  passwd[i] = '\0';
  return 0;
}


Avatar of mkandre

ASKER

Thanks, but you should have returned passwd instead of 0.

 /* Backspace or Delete backs up */
    if ((ch == '\b') || (ch == '\377')) {
      if (i > 0) i--;
      else putch('\a');
    } else {
      passwd[i++] = (char)ch;
      putch('*');
    }
  }
  passwd[i] = '\0';
  return 0; <======right here
}


Secondly at the point

>if(i > 0) i--;
>  else putch('\a');

i want to print a backspace character so that it removes the last * printed

something like

if(i>0) {i--; putch('\b');}
   else putch('\a');

the problem with '\b' is that it only moves the cursor back one space, not delete the last printed character.

suggestion...

ASKER CERTIFIED SOLUTION
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mkandre

ASKER

Thank you! This was a relatively easy question, I just wanted to give some points away.

You've earned it, so 10 bonus points.

mkandre.