Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to tokenize string to array of int in c?

Tags:

arrays

c

numbers

Anyone got anything about reading a sequential number from text file per line and parsing it to an array in C?

What I have in a file:

12 3 45 6 7 8
3 5 6 7
7 0 -1 4 5

What I want in my program:

array1[] = {12, 3, 45, 6, 7, 8};
array2[] = {3, 5, 6, 7};
array3[] = {7, 0, -1, 4, 5};

I've been through several ways to read it, but the only matter is only when i want to tokenize it per line. Thank you.

like image 255
van_tomiko Avatar asked Sep 27 '09 09:09

van_tomiko


1 Answers

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

like image 193
ChrisF Avatar answered Sep 21 '22 01:09

ChrisF