c - 如何复制存储在 strtok() token 中的字符串?

标签 c strtok

我正在尝试复制 strtok() 标记的值。

我在 string 上运行 strtok(),其值是 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() 做的是复制 token 的值,并将重复的值存储在数组中。

最佳答案

将您的代码转换为 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 个字符,依此类推。但是您的代码安全地将 token 复制到您的数组中。

这是更通用的代码,使用 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]

关于c - 如何复制存储在 strtok() token 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40054995/

相关文章:

c - 禁止移动具有某些标题的窗口

c - 如何将 SIGALRM 传递给在微秒内完成执行的程序?

c - 需要关于 strtok 函数的想法?

C strtok 没有标记空标记值

c - 使用 strtok() 的正确方法是什么?

c - strcpy 导致 C 程序崩溃

c - 如何在编辑控件中垂直居中文本?

c - 为什么 scanf 会导致我的代码无限期运行?

c - 使用 strtok() 将数值存储在二维数组中

使用 strtok 的 C 标记化打印出意外的值并阻碍了我的 strtol 验证