C program to convert input string of space separated ints into an int array -


question:

i want make c program takes string of space separated ints input (positive , negative, variable number of digits) , converts string int array.

there question on reading ints string input array on stack overflow doesn't work numbers of digit length more 1 or negative numbers.

attempt:

#include <stdio.h> int main () {   int arr[1000], length = 0, c;   while ((c = getchar()) != '\n') {     if (c != ' ') {       arr[length++] = c - '0';     }   }   printf("[");   ( int = 0; < length-1; i++ ) {     printf("%d,", arr[i]);   }   printf("%d]\n", arr[length-1]); } 

if enter following terminal:

$ echo "21 7" | ./run $ [2,1,7] 

this array get: [2,1,7] instead of [21,7]

if enter following:

$ echo "-21 7" | ./run $ [-3,2,1,7] 

i get: [-3,2,1,7] instead of [-21,7] makes no sense.

however, if enter:

$ echo "1 2 3 4 5 6 7" | ./run $ [1,2,3,4,5,6,7] 

note: assuming input string of space separated integers.

complete program (adapted this answer @onemasse) (no longer needs invalid input stop reading input):

#include <stdio.h> #include <stdlib.h>  int main () {     int arr[1000], length = 0, c, bytesread;     char input[1000];     fgets(input, sizeof(input), stdin);     char* input1 = input;     while (sscanf(input1, "%d%n", &c, &bytesread) > 0) {         arr[length++] = c;         input1 += bytesread;     }     printf("[");     ( int = 0; < length-1; i++ ) {         printf("%d,", arr[i]);     }     printf("%d]\n", arr[length-1]);     return 0; } 

from scanf/sscanf man page:

these functions return number of input items assigned. can fewer provided for, or zero, in event of matching failure.

therefore, if return value 0, know wasn't able convert anymore.

sample i/o:

$ ./parse 1 2 3 10 11 12 -2 -3 -12 -124 [1,2,3,10,11,12,-2,-3,-12,-124] 

note: unsure of how works. it. however, if understands, please edit post or leave comment.


Comments

Popular posts from this blog

wordpress - (T_ENDFOREACH) php error -

Export Excel workseet into txt file using vba - (text and numbers with formulas) -

Using django-mptt to get only the categories that have items -