简体   繁体   English

关于 scanf() 的奇怪跳过

[英]Strange skipping concerning scanf()

I've been trying out a few things with linked lists, mostly because I wanted to find a way to determine the length of a sequence determined by user input.我一直在尝试使用链表做一些事情,主要是因为我想找到一种方法来确定由用户输入确定的序列的长度。 The problem is问题是

Output in Terminal终端输出

[filip@filip PointerCheck]$ ./PointerCheck.o 
Enter number to populate the list..
1 2 3
c
Enter number to populate the list..
Printing...
1 2 3 
3

Why is the second population of the list skipped?为什么跳过列表的第二个群体?

I have tried multiple things and I believe that the problem resides somewhere within the while-loop's condition, concerning scanf();我尝试了多种方法,我相信问题出在 while 循环条件中的某个地方,与scanf();有关scanf();
The list functions should be working properly because a separate call from add_to_list() does actually insert an integer within the list, and print_list() prints all of them.列表函数应该可以正常工作,因为来自add_to_list()的单独调用确实在列表中插入了一个整数,并且print_list()打印了所有这些。 So I guess, it must be the while-loop, specifically scanf();所以我猜,一定是while循环,特别是scanf();

C Code C代码

void user_input_list(void) {
  int *input = NULL;
  input = (int *) malloc(sizeof(int));
  printf("Enter number to populate the list..\n");
  while (scanf("%d", input)) {
    add_to_list(*input, 1);
  }
}

int main(int argc, char const *argv[]) {
  int i = 0;
  struct node *ptr = NULL;

  user_input_list();

  user_input_list();

  print_list();
  printf("%d\n", lenght_list());

  return 0;
}

Here is the entire file, live [link] and on pastebin这是整个文件,live [link]pastebin

It looks like you are entering a non-numeric character to signal the end of input.看起来您正在输入一个非数字字符来表示输入结束。 But, the first nonmatching character encountered by scanf() is left in the input stream.但是, scanf()遇到的第一个不匹配字符留在输入流中。 So, you need to clear the extra characters from the input stream before attempting to read from it again.因此,您需要在尝试再次读取输入流之前清除输入流中的额外字符。 The standard way to do this is:执行此操作的标准方法是:

int c;

while ((c = getchar()) != '\n' && c != EOF)
    continue;

This discards the characters in the input stream until a newline or EOF is reached.这会丢弃输入流中的字符,直到到达换行符或EOF Note that getchar() returns EOF in the event of an error, and a user may also input EOF , so it is necessary to test for it explicitly in order to avoid a possible infinite loop.请注意, getchar()在发生错误时返回EOF ,并且用户也可能输入EOF ,因此有必要对其进行显式测试以避免可能的无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM