如何复制存储在strtok()标记中的字符串?

时间:2016-10-15 04:36:48

标签: c strtok

我正在尝试复制strtok()令牌的值。

我正在strtok()string运行volatile

char buffer[100];
char temp[100];
for(int i = 0; i < 100; i++){
    fgets(buffer, 100, my_file);
    fscanf(my_file, "%s", temp)
}

在这种情况下,temp的示例值可能是“100,200,300”

char my_array[3][100];
char* token;
token = strtok(temp,",");
while(token != NULL){
    switch (token[0]){
        case '1' :
        strcpy(my_array[0], token);
        break;
        case '2' :
        strcpy(my_array[1], token);
        break;
        case '3' :
        strcpy(my_array[2], token);
        break;
    }
    token = strtok(NULL,",");
}

我正在尝试使用strcpy()复制令牌的值,并将重复值存储在数组中。

1 个答案:

答案 0 :(得分:2)

将代码转换为MCVE(Minimal, Complete, Verifiable Example),我得到:

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

int main(void)
{
    char temp[] = "100,200,300";
    char my_array[3][100];
    char *token = strtok(temp, ",");

    while (token != NULL)
    {
        switch (token[0])
        {
        case '1':
            strcpy(my_array[0], token);
            break;
        case '2':
            strcpy(my_array[1], token);
            break;
        case '3':
            strcpy(my_array[2], token);
            break;
        }
        token = strtok(NULL, ",");
    }
    for (int i = 0; i < 3; i++)
        printf("%d: [%s]\n", i, my_array[i]);
    return 0;
}

来自运行的输出:

0: [100]
1: [200]
2: [300]

目前尚不清楚您的代码存在什么问题。

这显然不是一般解决方案。它依赖于从三个数字1,2,3开始的三个令牌,并且正好有3个令牌,并且没有任何令牌超过99个字符,依此类推。但是你的代码可以安全地将令牌复制到你的数组中。

这是更通用的代码,使用POSIX(但不是C)标准函数strdup()

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

int main(void)
{
    char temp[] = "100,200,300,19231,Exploratorium,Extraneous material,91"
                  "9293,and one rather long token without much significance"
                  " except to point out that not all strings are as short as"
                  " 100 bytes long";
    char *my_array[100];
    int count = 0;

    char *token = strtok(temp, ",");
    while (token != NULL)
    {
        if (count >= 100)
            break;
        my_array[count++] = strdup(token);
        token = strtok(NULL, ",");
    }

    for (int i = 0; i < count; i++)
        printf("%d: [%zu][%s]\n", i, strlen(my_array[i]), my_array[i]);

    for (int i = 0; i < count; i++)
        free(my_array[i]);
    return 0;
}

这会产生输出:

0: [3][100]
1: [3][200]
2: [3][300]
3: [5][19231]
4: [13][Exploratorium]
5: [19][Extraneous material]
6: [6][919293]
7: [123][and one rather long token without much significance except to point out that not all strings are as short as 100 bytes long]