[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: strtok problem



plmanikandan@xxxxxxxxx wrote:
> Hi,
> I need to split the value stored in a string and store them to another
> charrecter array.I am using strtok function.But i am getting invalid
> output when there is no value between delimiter
>
> my code
> #include<stdio.h>
> #include<string.h>
> #include<stdlib.h>
> void main()
> {
>
> char *pch;
> char *parameters[4];
> int paramcount=0;
>
> char b[]="mani,raju,musa,kumar";
>
> pch=strtok(b,",");
> while (pch != NULL)
> {
>    //parameters[paramcount]=pch;
> parameters[paramcount]=(char*)malloc(strlen(pch) + 1);
> strcpy(parameters[paramcount],pch);
> paramcount++;
>   pch = strtok (NULL, ",");
>  }//while (pch != NULL)
>
> for(int t=0;t<4;t++)
> printf("\n%s\n",parameters[t]);
>
> }
> the above code works fine.when i change the input as follows
> char b[]="mani,,,kumar"
> The output is not correct.
> How to free the memory allocated?
> how to handle strtok when there is no value between delimiter

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

int main(void)
{

    char *pch;
    char *parameters[4];
    int  paramcount = 0;

    char b[] = "mani,,,kumar";

    pch = strtok(b,",");

    while (pch != NULL)
    {
        if(strlen(pch))
        {
            parameters[paramcount] = malloc(strlen(pch) + 1);

            strcpy(parameters[paramcount++], pch);

            pch = strtok (NULL, ",");
        }
    }

    for(int t=0;t< paramcount;t++)
    {
        printf("\n%s\n",parameters[t]);
    }

    while(--paramcount >= 0)
    {
        printf("\t%s\n",parameters[paramcount]);

        free(parameters[paramcount]);
    }

    return 0;
}


-- 
==============
Not a pedant
============== 





Home | Main Index | Thread Index 6126 6841 7235 12182 21254 25899 32315 33145 36696 48473

9/8/2010 9:57:09 GMT