Home > Net >  Add parsed elements from text file to array
Add parsed elements from text file to array

Time:11-22

I am trying to write a code that fetches lines from a txt file and adds parsed out variables from those lines to an array. The txt file reading and the parsing works perfectly.

My text file "inventory.txt" looks like this:

Mars;6
Snickers;7
Bounty;2
Twix;4
MilkyWay;6
KitKat;8

This is my code:

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

int main() {

    //INITIALIZE
    char line[100];
    char *elements[100] = {};
    int i_stock[100];
    int r2 = 0;

    char item[20] = {0};
    int stock;

    //DEFINE FILE
    FILE *the_file = fopen("inventory.txt","r");

    //CHECK IF FILE EXISTS
    if(the_file == NULL) {
        perror("Inventarfehler");
        exit(1);
    }

    //SCAN LINES FOR STOCK
    while(fgets(line, sizeof(line), the_file)) {
        sscanf(line, "%[a-zA-Z];%d", &item, &stock);
        
        //ADD VAR TO ARRAY
        elements[r2] = item;
        r2  ;
    }
    
    printf(elements[2]);
    return 0;
}

Whatever index of elements I print, it is always KitKat. My code keeps overwriting the variables.

printf("%s",elements[2]) should print out Bounty.

Could anyone help me solve this? Thanks in advance!

CodePudding user response:

The problem is that all of your elements are simple references to item whose content will ultimately be the last candy bar name you read.

Here is one way to solve this problem, by copying each parsed string to a newly-allocated string on the heap using strdup():

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

#define MAX_COUNT 100

int main()
{

    //INITIALIZE
    char line[MAX_COUNT];
    char *elements[MAX_COUNT] = {};
    int i_stock[MAX_COUNT];
    int r2 = 0;

    char item[20] = {0};
    int stock;

    //DEFINE FILE
    FILE *the_file = fopen("inventory.txt", "r");

    //CHECK IF FILE EXISTS
    if (the_file == NULL)
    {
        perror("Inventarfehler");
        exit(1);
    }

    //SCAN LINES FOR STOCK
    while (r2 < MAX_COUNT && fgets(line, sizeof(line), the_file))
    {
        sscanf(line, "%[a-zA-Z];%d", item, &stock);

        //ADD VAR TO ARRAY
        elements[r2] = strdup(item);
        r2  ;
    }

    printf("%s\n", elements[2]);

    // Free allocated memory
    for (int ii = 0; ii < r2; ii  )
    {
        // printf("Free elements[%d]: %s\n", ii, elements[ii]);
        free(elements[ii]);
        elements[ii] = NULL;
    }

    return 0;
}
  •  Tags:  
  • c
  • Related