读取空格将stdin中的数字分隔为链表

时间:2016-01-15 06:34:57

标签: c scanf stdin

我正在尝试读取从stdin到c程序的空格分隔的数字以及每个数字我将节点添加到链接列表。

从stdin输入:

20
20 30 123 34 50

stdin(20)的第一行是查找编号为20的项目。 第二行包含要插入链接列表的数据项 一旦进入它应该结束循环,但它不是,我不知道我在这里错过了什么。

  char follow;
  scanf("%d", &M);
  while(((count = scanf("%d%c", &element, &follow)) > 0))
    {
      if(count == 2 && isspace(follow) || count == 1)
        {
          printf("count = %d and element = %d\n", count, element);
          push(&root, element);
        }
      else{
        break;
      }
    }

问题是while循环在按Enter键时不会结束。

1 个答案:

答案 0 :(得分:1)

您可以更改if条件,如下所示:

if ((count == 2 && isspace(follow) && follow != '\n') || count == 1)

因为空格' '和换行符'\n'都是空格,isspace本身是不够的。

相关问题