【问题标题】:How to separate a string into parts and store into an array in C?如何将字符串分成几部分并存储到C中的数组中?
【发布时间】:2020-10-17 23:09:40
【问题描述】:

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

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], " "),但我真的很难将它应用到这段代码中。

【问题讨论】:

  • 您应该显示您尝试过的代码以及使用它时发生的情况。 strtok 是一个“狡猾”的野兽。
  • 我会尝试追溯代码,并编辑帖子。

标签: arrays c loops file


【解决方案1】:

你可以写一个函数(str_to_word_array) 这是我的 str_to_word_array 函数 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);

【讨论】:

    【解决方案2】:

    已解决:

    在 cmets 中的 brahimi haroun 的帮助下,我制作了一个单独的函数来单独执行任务,效果很好。我想我会在这里分享它:

    char **get_column_item(char *lines, int column)
    {
        int i = 0;
        char *p = strtok(lines, " ");
        char *array[4];
    
        while (p != NULL)
        {
            array[i++] = p;
            p = strtok(NULL, " ");
        }
    
        printf("%s\n", array[column]);
    
        return array[column];
    }
    

    现在,使用我的原始代码,如果您调用 get_column_item(line[1], 0);它将返回该行中的第一项,因此它将返回“Chicken”。

    【讨论】:

    • strtok() 如果其中一个字段为空(两个连续的空格),将会惨遭失败。基本上,strtok() 只是无法使用。
    猜你喜欢
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多