title: C program to convert input string of space separated ints into an int array
body: <p><strong>Question:</strong></p>
  
  <p>I want to make a C program that takes a string of space separated ints as input (positive and negative, variable number of digits) and converts the string to an int array.</p>
  
  <p>There is another question on reading ints from a string input into an array on Stack Overflow but it doesn't work for numbers of digit length more than 1 or negative numbers.</p>
  
  <p><strong>Attempt:</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main () {
    int arr[1000], length = 0, c;
    while ((c = getchar()) != '\n') {
      if (c != ' ') {
        arr[length++] = c - '0';
      }
    }
    printf("[");
    for ( int i = 0; i &lt; length-1; i++ ) {
      printf("%d,", arr[i]);
    }
    printf("%d]\n", arr[length-1]);
  }
  </code></pre>
  
  <p>If I enter the following into terminal:</p>
  
  <pre><code>$ echo "21 7" | ./run
  $ [2,1,7]
  </code></pre>
  
  <p>This is the array I get: [2,1,7] instead of [21,7]</p>
  
  <p>If I enter the following:</p>
  
  <pre><code>$ echo "-21 7" | ./run
  $ [-3,2,1,7]
  </code></pre>
  
  <p>I get: [-3,2,1,7] instead of [-21,7] which makes no sense.</p>
  
  <p>However, if I enter:</p>
  
  <pre><code>$ echo "1 2 3 4 5 6 7" | ./run
  $ [1,2,3,4,5,6,7]
  </code></pre>
  
  <p>Note: I am assuming that the input it always a string of space separated integers.</p>