1

我正在尝试使用 strtok 和 strcat 但第二个 printf 从未出现。这是代码:

int i = 0;
char *token[128];
token[i] = strtok(tmp, "/");
printf("%s\n", token[i]);
i++;
while ((token[i] = strtok(NULL, "/")) != NULL) {
    strcat(token[0], token[i]);
    printf("%s", token[i]);
    i++;
}

如果我的输入是 tmp 的 1/2/3/4/5/6,那么控制台输出将是 13456。总是缺少 2。有谁知道如何解决这一问题?

4

2 回答 2

3

The two is always missing because on the first iteration of your loop you overwrite it with the call to strcat.

After entry to the loop your buffer contains: "1\02\03/4/5/6" internal strtok pointer is pointing to "3". tokens[1] points to "2".

You then call strcat: "12\0\03/4/5/6" so your token[i] pointer is pointing to "\0". The first print prints nothing.

Subsequent calls are OK because the null characters do not overwrite the input data.

To fix it you should build up your output string into a second buffer, not the one you are parsing.

A working(?) version:

#include <stdio.h>
#include <string.h>
int main(void)
{
    int i = 0;
    char *token[128];
    char tmp[128];
    char removed[128] = {0};
    strcpy(tmp, "1/2/3/4/5/6");
    token[i] = strtok(tmp, "/");
    strcat(removed, token[i]);
    printf("%s\n", token[i]);
    i++;
    while ((token[i] = strtok(NULL, "/")) != NULL) {
        strcat(removed, token[i]);
        printf("%s", token[i]);
        i++;
    }
    return (0);
}
于 2011-09-14T16:47:12.907 回答
0

strtok modifies the input string in place and returns pointers to that string. You then take one of those pointers (token[0]) and pass it to another operation (strcat) that writes to that pointer. The writes are clobbering each other.

If you want to concatenate all the tokens, you should allocate a separate char* to strcpy to.

于 2011-09-14T16:45:23.360 回答