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

从getchar()读取输入,产生意外结果,c,io,scanf,getchar,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 ch

我有一个函数,它从终端读取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)

有人能解释我为什么会出现这种行为以及如何解决它吗?

在读取第二个PIN之前,您需要使用尾随的换行符。例如,
read\u pin()
的两个调用之间的一个简单的
getcher()
,将为您产生有趣的结果

当您输入时,随后按enter键。“回车”是换行符,它期待被消费。

将第一个
getchar()
移出
read\u pin()

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

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

scanf

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

将其放在scanf

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

猜猜看

因为
old\u pin\u len
new\u pin\u len
充当索引,将它们初始化为
0

int old_pin_len = 0;
int new_pin_len = 0;

“在读取第二个PIN之前使用尾随换行符”OP在这里不是这样做的:
while(((ch=getchar())!='\n'))
但是在这两个read\u PIN()调用之间添加fflush(stdin)之后,我得到了相同的结果。如果我在while()循环之前删除getchar(),我将无法获取PIN,我应该怎么做才能修复它。@PrateekJoshi:不要执行
fflush(stdin)
,因为它会导致未定义的行为。alk我明白你的意思了@PrateekJoshi,你需要向我们展示更多的代码,比如展示整个main。您调用getchar和scanf的顺序一定有问题。我同意alk的
fflush()
。最好有一个简单的示例,例如长度等。请在调用read_pin之前显示对scanf的调用。@alk更新的问题以显示scanf()。
选项是如何定义的?现在,我没有第一次得到输入pin的提示,它会自动换行并退出。现在,我第一次没有收到输入PIN的提示,它会自动换行并退出。@PrateekJoshi您需要显示您的
main
函数,也请提供。
int old_pin_len = 0;
int new_pin_len = 0;