【问题标题】:Strange skipping concerning scanf()关于 scanf() 的奇怪跳过
【发布时间】:2017-01-05 23:06:23
【问题描述】:

我一直在尝试使用链表做一些事情,主要是因为我想找到一种方法来确定由用户输入确定的序列长度。问题是

终端输出

[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

为什么会跳过列表的第二个填充?

我已经尝试了多种方法,并且我认为问题存在于 while 循环的某个地方,与 scanf();
有关 列表函数应该可以正常工作,因为来自add_to_list() 的单独调用实际上会在列表中插入一个整数,并且print_list() 会打印所有这些。所以我猜,它一定是while循环,特别是scanf();

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;
}

这是整个文件,live [link]pastebin

【问题讨论】:

  • 一般情况下,不要使用scanf 进行用户输入。 (尝试在此站点中搜索 c scanf 并查看关于意外 scanf 行为的 5000 个重复问题。)
  • 您未发布的代码中是否有scanf("%c", ...)
  • 顺便说一句,你的循环条件是错误的:它应该是scanf(...) == 1,而不仅仅是scanf(...)scanf 可能会以有趣的方式失败。
  • 那个链接是垃圾。可怕的彩色和不可读的代码以及对弹出窗口的侵入性要求。
  • 不要链接到外部网站。

标签: c while-loop linked-list scanf


【解决方案1】:

您似乎正在输入一个非数字字符来表示输入结束。但是,scanf() 遇到的第一个不匹配字符会留在输入流中。因此,您需要先从输入流中清除多余的字符,然后再尝试从中读取。执行此操作的标准方法是:

int c;

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

这会丢弃输入流中的字符,直到到达换行符或EOF。注意getchar()在出错时会返回EOF,用户也可以输入EOF,所以需要显式测试,以避免可能的死循环。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 2021-08-27
    • 2011-11-28
    相关资源
    最近更新 更多