简体   繁体   中英

How to separate a string into parts and store into an array in C?

I have a text file that lists some groceries and information about them. Looks something like this:

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

Here's my code that I've used that allows me to reference each individual line:

#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;
}

For instance, if I print line[1], I will get "Chicken 1kg 7.21 7.50". What I need to do however, is separate each string into their individual parts. So if I call something like line[1][0], I will get only "Chicken" as a result. I've tried using strtok(line[i], " ") in some for loops and other things like that, but I'm really stumped about how to apply it to this code.

you can write a function (str_to_word_array) this is my str_to_word_array func https://github.com/la-montagne-epitech/mY_Lib_C/blob/master/my_str_to_word_array.c it's take a string and a separator( " " for your case), you have to stock the result in char **, just like this:

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

SOLVED:

With the help of brahimi haroun in the comments, i made a separate function to perform the task seperately and it works great. I thought I would share it here:

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];
}

Now, with my original code, if you call get_column_item(line[1], 0); It will return the first item in that row, so it will return "Chicken".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM