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;
}

Recommended Answers

All 2 Replies

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?

Member Avatar for MonsieurPointer

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:

  1. One which will dynamically add elements to a C-type string array (char **).
  2. 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:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.