从getchar()读取输入会产生意外结果 [英] Reading input from getchar() giving unexpected results
本文介绍了从getchar()读取输入会产生意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从终端读取PIN并将PIN和PIN长度存储在传递的变量中的功能.在第一次调用该函数时,我输入了预期的PIN和PIN长度.但是,在第二次调用此函数期间,第一个字符被省略.
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;
}
此函数的调用:
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?
推荐答案
将第一个 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
调用之后.
and place it right after the scanf
call before it calls read_pin()
the 1st time.
printf("\nSelect session : ");
scanf("%d", &option);
getchar();
这篇关于从getchar()读取输入会产生意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文