how to tokenize string to array of int in c? how to tokenize string to array of int in c? arrays arrays

how to tokenize string to array of int in c?


The following code will read a file a line at a time

char line[80]FILE* fp = fopen("data.txt","r");while(fgets(line,1,fp) != null){   // do something}fclose(fp);

You can then tokenise the input using strtok() and sscanf() to convert the text to numbers.

From the MSDN page for sscanf:

Each of these functions [sscanf and swscanf] returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. The return value is EOF for an error or if the end of the string is reached before the first conversion.

The following code will convert the string to an array of integers. Obviously for a variable length array you'll need a list or some scanning the input twice to determine the length of the array before actually parsing it.

char tokenstring[] = "12 23 3 4 5";char seps[] = " ";char* token;int var;int input[5];int i = 0;token = strtok (tokenstring, seps);while (token != NULL){    sscanf (token, "%d", &var);    input[i++] = var;    token = strtok (NULL, seps);}

Putting:

char seps[]   = " ,\t\n";

will allow the input to be more flexible.

I had to do a search to remind myself of the syntax - I found it here in the MSDN


What I would do is to make a function like this:

size_t read_em(FILE *f, int **a);

In the function, allocate some memory to the pointer *a, then start reading numbers from the f and storing them in *a. When you encounter a newline character, simply return the number of elements you've stored in *a. Then, call it like this:

int *a = NULL;FILE *f = fopen("Somefile.txt", "r");size_t len = read_em(f, &a);// now a is an array, and len is the number of elements in that array

Useful functions:

  • malloc() to allocate an array.
  • realloc() to extend a malloc()ed array
  • fgets() to read a line of text (or as much as can be stored).
  • sscanf() to read data from a string (such as a string returned by fgets()) into other variables (such as an int array created by malloc() - hint hint)


I'd strongly suggest NOT to use sscanf and friends when the number of fields is variable.Use strtok and atoi. Just make sure to read the strtok manpage well, many programmers I know find its syntax a bit surprising in the beginning. Also note that strtok will modify the input string, so you may want to work on a copy.