Get Strings with Strtok in C
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 th开发者_JAVA百科is... 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 strcat
into a readonly, empty string. Rather, you have to provide your own target string:
char others[1000] = { 0 };
char * tmp;
// ...
while ((tmp = strtok(NULL, " ")) != NULL)
{
strcat(others, tmp);
}
You also used input
and tmp
wrong; you should be checking the result of strtok
before processing it.
This is somewhat dangerous since you have no control over the resulting string length. You should use strncat
instead, but that means you'll also have to keep count of the appended characters.
You should be checking
while (tmp != NULL)
Also, "others" doesn't point to any allocated memory, so I'd expect this to crash until you fix that.
There are several flaws with the code:
Assuming, others
is a character array, you can't work with it in that manner. You have to allocate sufficient memory.
Also, the condition should be
while(tmp != NULL)
Also, the statment second = strtok ( NULL, " " );
is redundant, you should be doing this inside the loop.
精彩评论