Search code examples
cioscanfgetchar

Reading input from getchar() giving unexpected results


I have a function which reads PIN from terminal and stores PIN and PIN length in the variables passed. On the first call to the function I get expected PIN and PIN length entered. However, during the second call to this function the first character is omitted.

/*
 * Function : read_pin(char *pin,int *pin_len)
 * Description : Read entered PIN and stores PIN in pin and pin length in pin_len
 */
int read_pin(unsigned char *pin,unsigned int *pin_len)
{
    int err = EXIT_SUCCESS;
    char ch;

    fflush(stdout);

    /* Pause to get pin (if removed, input is not read from terminal)*/
    getchar();     // i think,this is causing PROBLEM

    while( ((ch = getchar()) != '\n') )
    {
        pin[*pin_len] = ch;
        (*pin_len)++;
    }

    /* If newline at the end of the pin. You'll have to check that */
    if( pin[*pin_len-1] == '\n' )
    {
        pin[*pin_len-1] = '\0';
    }

    exit:
        return err;
}

Calling of this function:

printf("\nSelect session : ");
scanf("%d", &option);

printf("\nEnter old PIN: ");
read_pin(old_pin, &old_pin_len); // input: "1234" got: "1234"

fflush(stdout);

printf("\nEnter new PIN: ");
read_pin(new_pin, &new_pin_len); //input: "12345" got: "2345" (1 is omitted)

Can someone explain me why I am getting this kind of behaviour and how to fix it?


Solution

  • Move the 1st getchar() out of read_pin()

    int read_pin(unsigned char *pin,unsigned int *pin_len)   
    {
      int err = EXIT_SUCCESS;
      int ch;  /* getchar() returns int! */
    
      fflush(stdout);
    
      /* Pause to get pin (if removed, input is not read from terminal)*/
    
      while( ((ch = getchar()) != '\n') )
    

    and place it right after the scanf call before it calls read_pin() the 1st time.

      printf("\nSelect session : ");
      scanf("%d", &option);
      getchar();