-3

I have a char array containing bicho,25,25-04-2000. I want to extract bicho and put it in a variable and the same goes for 25 and 25-04-2000.

I tried strtok() and sscanf, but no luck at all.

here is my method that i used:

fp = fopen(fn,"r");
while(!feof(fp)){
  fgets(data, 255,fp);
  puts(data);
  pch = strtok (data,",");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, ",");
  }
}


I want to store each value in separate variable not print it.

Hachemi Hamadi
  • 103
  • 2
  • 9

1 Answers1

0

Your use of feof is not necessary. You can use fgets as the loop condition. Then it is just a matter of storing the strings in an array. You can then numerically convert your number with strtol or atoi (if needed). For example, you could do something like:

#define MAXL 10
#define MAXC 32

char array[MAXL][MAXC] = {{0}};
size_t index = 0;

if (!(fp = fopen (fn, "r"))) {
    fprintf (stderr, "error: file open faied '%s'.\n", fn);
    return 1;
}

while (fgets (data, 255,fp)) 
{
    char *p = data;
    if ((p = strtok (data, ","))) {
        size_t plen = strlen (p);
        if (plen + 1 < MAXC)
            strncpy (array[index++], p, plen + 1);
        else
            fprintf (stderr, "error: string exceeded MAXC\n");

        while (index < MAXL && (p = strtok (NULL, ",\n")) != NULL)
        {
            plen = strlen (p);
            if (plen + 1 < MAXC)
                strncpy (array[index++], p, plen + 1);
            else
                fprintf (stderr, "error: string exceeded MAXC\n");
        }
    }
}

Using a for Loop

You can do the same thing with a for loop a bit more efficiently:

while (fgets (data, 255,fp) 
{
    char *p = data;
    for (p = strtok (data, ","); index < MAXL && p; p = strtok (NULL, ",\n"))
    {
        size_t plen = strlen (p);
        if (plen + 1 < MAXC)
            strncpy (array[index++], p, plen + 1);
        else
            fprintf (stderr, "error: string exceeded MAXC\n");    
    }
}

note: by confirming the length plen before you copy to your array, you can insure your strings are nul-terminated. Let me know if you have further questions.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85