scanf函数/ getchar函数正常工作只有第一次通过循环? [英] scanf/getchar working correctly only first time through loop?
问题描述
我试图让用户在一些他们想要进入的次数(并为每个号码的链表节点)。
I'm trying to have the user enter in a number as many times as they want (and create a linked list node for each of the numbers).
清除文字输入缓冲器,但无济于事不过,我试过多种方法。奇怪的是,code将通过执行一次,但不能正确地执行第二。
However, I've tried multiple method of clearing the character input buffer but to no avail. Strangely, the code will execute once through but not execute correctly the second.
例如,与下面的code,终端读取:
For example, with the code below, the terminal reads:
would you like to enter an integer?
y
Enter an integer: 4
would you like to enter an integer?
y
**program terminates**
和我使用 scanf函数(%C,YESNO)时前;
我甚至不能够输入Y的最后一行。它只是终止。
And before when I was using scanf("%c", yesno);
I would not even be able to input 'y' on the last line. It just terminated.
struct node *read_numbers(void){
struct node *first = NULL;
int n; char yesno;
yesno = 'y';
while( yesno == 'y'){
printf("Would you like enter an integer ((y) for yes/(n) for no):\n");
yesno = getchar();
while(getchar() != '\n');
if(yesno == 'y'){
printf("Enter an Integer:");
scanf(" %d", &n);
first = add_to_list(first, n);
} else {
return first;
}
} // end while
}
我在文字输入和缓冲区读取了,按说的getchar()方法应该工作。我在使用它错了吗?我也试过scanf()函数与%C前后多余的空格,但无济于事。
I read up on character inputs and buffers, and supposedly the getchar() method should work. Am I utilizing it wrong? I've also tried scanf() with extra spaces before and after the "%c", but to no avail.
推荐答案
您需要scanf函数后消化换行符。你可以做你的code上面做什么:
You need to digest the newline after the scanf. You can do what you're doing above in the code:
scanf(" %d", &n);
while(getchar() != '\n');
first = add_to_list(first, n);
这篇关于scanf函数/ getchar函数正常工作只有第一次通过循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!