cscanf

How to get integer input in an array using scanf in C?


I am taking multiple integer inputs using scanf and saving it in an array

while(scanf("%d",&array[i++])==1);

The input integers are separated by white spaces for example:

12 345 132 123

I read this solution in another post.

But the problem is the while loop is not terminating.

What's the problem with this statement?


Solution

  • OP is using the Enter or '\n' to indicate the end of input and spaces as number delimiters. scanf("%d",... does not distinguish between these white-spaces. In OP's while() loop, scanf() consumes the '\n' waiting for additional input.

    Instead, read a line with fgets() and then use sscanf(), strtol(), etc. to process it. (strtol() is best, but OP is using scanf() family)

    char buf[100];
    if (fgets(buf, sizeof buf, stdin) != NULL) {
      char *p = buf;
      int n;
      while (sscanf(p, "%d %n", &array[i], &n) == 1) {
         ; // do something with array[i]
         i++;  // Increment after success @BLUEPIXY
         p += n;
      }
      if (*p != '\0') HandleLeftOverNonNumericInput();
    }