首页 > 解决方案 > 如何将字符串分成几部分并存储到C中的数组中?

问题描述

我有一个文本文件,其中列出了一些杂货和有关它们的信息。看起来像这样:

Round_Steak 1kg 17.38 18.50
Chicken 1kg 7.21 7.50
Apples 1kg 4.25 4.03
Carrots 1kg 2.3 2.27

这是我使用的代码,它允许我引用每一行:

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

#define Llimit 100
#define Rlimit 10 

int main()
{
    //Array Line gets each line from the file by setting a limit for them and printing based on that limit.
    char line[Rlimit][Llimit];
    FILE *fp = NULL; 
    int n = 0;
    int i = 0;

    fp = fopen("food.txt", "r");
    while(fgets(line[n], Llimit, fp)) 
    {
        line[n][strlen(line[n]) - 1] = '\0';
        n++;
    }
    
    printf("%s", line[1]);
    
    fclose(fp);
    return 0;
}

例如,如果我打印 line[1],我将得到“Chicken 1kg 7.21 7.50”。然而,我需要做的是将每个字符串分成各自的部分。因此,如果我调用 line[1][0] 之类的东西,结果我只会得到“Chicken”。我已经尝试在一些 for 循环和其他类似的东西中使用 strtok(line[i], " ") ,但我真的很困惑如何将它应用到这段代码中。

标签: arrayscloopsfile

解决方案


你可以写一个函数(str_to_word_array)这是我的str_to_word_array func https://github.com/la-montagne-epitech/mY_Lib_C/blob/master/my_str_to_word_array.c 它需要一个字符串和一个分隔符(“”对于你的情况) ,您必须将结果存储在 char ** 中,就像这样:

char *line; // type of the element
char separator // type of the element
char **tab = my_str_to_word_array(line, separator);

推荐阅读