Reading input from getchar() giving unexpected results

喜夏-厌秋 提交于 2020-05-31 11:45:23

问题


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?


回答1:


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();



回答2:


You need getchar right after scanf

Hence

int read_pin(unsigned char *pin,unsigned int *pin_len)
{
    int err = EXIT_SUCCESS;
    char ch;

    fflush(stdout);

   ...........
    getchar();     // Remove this line

    .........

    exit:
        return err;
}

Place it right after scanf

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

Guess work.

Since old_pin_len and new_pin_len are acting as indexes initialize them to 0.

int old_pin_len = 0;
int new_pin_len = 0;



回答3:


You need to consume the trailing newline character, before reading the 2nd PIN. For example a simple getcher() between the two calls of read_pin() would produce interesting results for you.

When you input, you hit enter afterwards. That "enter" is the newline character, who looks forward to being consumed.



来源:https://stackoverflow.com/questions/53131468/reading-input-from-getchar-giving-unexpected-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!