从 getchar() 读取输入给出意想不到的结果

Reading input from getchar() giving unexpected results

我有一个函数可以从终端读取 PIN 并将 PIN 和 PIN 长度存储在传递的变量中。在第一次调用该函数时,我得到了预期的 PIN 和输入的 PIN 长度。但是,在第二次调用此函数时,第一个字符被省略。

/*
 * 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] = '[=10=]';
    }

    exit:
        return err;
}

调用此函数:

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)

谁能解释我为什么会出现这种行为以及如何解决?

在读取第二个 PIN 之前,您需要先使用尾随的换行符。例如,read_pin() 的两次调用之间的简单 getcher() 会为您产生有趣的结果。

当你输入的时候,你按下回车键。那个"enter"是换行符,期待被消费

将第一个 getchar() 移出 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') )

并在它第一次调用 read_pin() 之前将其放在 scanf 调用之后。

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

scanf

之后您需要 getchar

因此

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;
}

放在 scanf

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

猜对了。

由于 old_pin_lennew_pin_len 作为索引将它们初始化为 0

int old_pin_len = 0;
int new_pin_len = 0;