954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Store tokens in Array

Hi, I need help with this, I'm reading a txt file that has this format:
10,4,12,6,18,24,7,8,15,14,25,2
So far, I read the file using fopen ().Also, I used strtok () to split the string into tokens, but i don't know how store the tokens into an array.
any ideas?
thanks

#include <stdio.h>
#include <string.h>

int main()
{
   FILE * pFile;
   char mystring [100];
   char * datos; 
   pFile = fopen ("intermemory.txt" , "r");
   if ( fgets (mystring , 100 , pFile) != NULL )
   {
     puts (mystring);
     fclose (pFile);
   }
   
   //printf ("\nSplitting string \"%s\" into tokens:\n",mystring);
   datos = strtok (mystring,",");
   while (datos != NULL)
   {
    printf ("%s\n",datos);
    datos = strtok (NULL, ",");
   }
   return 0;
}
Ascar
Newbie Poster
1 post since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

The tokens are char*, right?
All you need is an array of char* of the size you need.
Keep a counter as an offset and increment it on each loop.

Are you keeping all of them?
How many pointers/tokens do you need?

thines01
Postaholic
Team Colleague
2,424 posts since Oct 2009
Reputation Points: 445
Solved Threads: 402
 

Since you are not likely to know the size of the array, you will need to allocate memory dynamically. To answer your question, an advanced knowledge of pointers is required.

Since neither the size of array, nor the length of each element is known, you will need to allocate a char** (pointer to pointer to char). The first pointer indicates the variable length of the element you want to add to the array, e.g. "1", "12", "256", etc. The second pointer indicates how many elements are in the array (1, 2, 3, ...).

You will need two functions:One which will dynamically add elements to a C-type string array (char **).
One which will free memory allocated by the first function.

Your function prototypes should have signatures like this:

void create_string_array(char *pString, char ***pppStrings, int *pNumStrings);
void free_string_array(char ***pppStrings, int *pNumStrings);


Now it's up to you to write the code for those functions. :icon_wink:

MonsieurPointer
Junior Poster
125 posts since Jun 2011
Reputation Points: 31
Solved Threads: 12
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: