从getchar()读取输入会产生意外结果

时间:2018-11-03 12:49:10

标签: c io scanf getchar

我有一个功能,可以从终端读取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] = '\0';
    }

    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)

有人可以解释一下我为什么会出现这种行为以及如何解决该问题吗?

3 个答案:

答案 0 :(得分:1)

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') )

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

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

答案 1 :(得分:1)

您需要在getchar之后紧随scanf

因此

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;

答案 2 :(得分:-1)

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

输入时,随后按Enter键。那个“输入”是换行符,他期待被消费。

相关问题