Monday, May 24, 2010

Split a string into 3 variables in C?

I have a string separated by commas, that I want placed into variables.





ex.


char string[50] = "here, it, is"





// SOME CODE EXECUTES





str1 = "here";


str2 = "it";


str3 = "is";








What code should I use?

Split a string into 3 variables in C?
You want to extract tokens from the string, given a delimiter. There is a function in C for this, called strtok.





http://cppreference.com/stdstring/strtok...
Reply:char str[50] = "here,it,is";





char *pch;


pch = strtok(str,","); //get token 1 - (here)





while(pch != NULL)


{


cout%26lt;%26lt;pch%26lt;%26lt;endl;


pch = strtok(NULL,","); //first get - (it) and then (is)


}





Hope this helps!


No comments:

Post a Comment