hello

I have the following

while(fgets(b2b_rates_address,1000,in_fp) != NULL )
{    
     strcpy(rates_details[j].ig1, strtok(b2b_rates_address,","));
     printf("rates_details[j].ig7 = %s\n",rates_details[j].ig1 );
     strcpy(rates_details[j].ig2,strtok(NULL,","));
     printf("rates_details[j].ig7 = %s\n",rates_details[j].ig2 );
     strcpy(rates_details[j].ig3,strtok(NULL,","));
     printf("rates_details[j].ig7 = %s\n",rates_details[j].ig3 );
     j++;
}

The issue i have is this:-
It works fine up to field ig3, this is due to the fact that this field may/may not be empty....the program then bombs out

How can I get round this? any code examples would be appreciated

Many Thanks

You are not validating the return value of strtok(). It returns NULL if its at the end of the string when you call strtok() with a NULL first parameter (or some other error occurred). It would be more prudent to code it like this:

char* ptr;
while(fgets(b2b_rates_address,1000,in_fp) != NULL )
{
     if( (ptr = strtok(b2b_rates_address,","))
     {
            strcpy(rates_details[j].ig1, ptr);
            printf("rates_details[j].ig7 = %s\n",rates_details[j].ig1 );
            if( (ptr = strtok(NULL,",") )
            {
                  strcpy(rates_details[j].ig2,ptr);
                  printf("rates_details[j].ig7 = %s\n",rates_details[j].ig2 );
                  if( (ptr = strtok(NULL, ","))
                  {
                      strcpy(rates_details[j].ig3, ptr);
                      printf("rates_details[j].ig7 = %s\n",rates_details[j].ig3 );
                   }
           }
     }
     j++;
}

>this field may/may not be empty
strtok ignores empty fields, so if that field is empty, you're actually processing a null pointer because there are fewer fields than you're expecting. If you want to get an empty string for the empty field, don't use strtok.

This article has been dead for over six months. Start a new discussion instead.