I want to split a string to 3 parts.
gets(input);
printf("\n%s\n",input);
first = strtok (input, " ");
second = strtok ( NULL, " " );
others = "";
while(input != NULL){
tmp = strtok ( NULL, " " );
strcat(others,tmp);
}
like this… So i want to get first word, second word into a string and others in a string. This code fails, how can i resolve this?
Strings in C aren’t magic, they’re character arrays. You cannot just
strcatinto a readonly, empty string. Rather, you have to provide your own target string:You also used
inputandtmpwrong; you should be checking the result ofstrtokbefore processing it.This is somewhat dangerous since you have no control over the resulting string length. You should use
strncatinstead, but that means you’ll also have to keep count of the appended characters.