yguw
yguw

Reputation: 844

Reading space separated numbers from stdin into a linked list

I am trying to read numbers separated by spaces from stdin into a c program and on every number I am adding a node to linked list.

Input from stdin:

20
20 30 123 34 50

The first line from stdin (20) is for looking up an item with number 20. The second line contains data items to inserted into a linked list Upon entering it should end the loop but it's not and I am not sure what I am missing out here.

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

The problem is that the while loop doesn't end on hitting enter.

Upvotes: 0

Views: 459

Answers (1)

Selçuk Cihan
Selçuk Cihan

Reputation: 2034

You would change your if conditional as in:

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

Because both space ' ' and newline '\n' are empty space, isspace itself is not enough.

Upvotes: 1

Related Questions