C separate string with commas in vectors

Asked

Viewed 245 times

0

I want to separate each line of a file into 2 vectors: v[i]. date and v[i].value. However, when I run the code no value I print is correct, and the outputs are random values. There’s something I should change?

Input
02/20/18,11403.7
02/19/18,11225.3
02/18/18,10551.8
02/17/18,11112.7
02/16/18,10233.9

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


typedef struct
{
    char *date;
    long int *value;
}vetor;

int main(int argc,char **argv)
{
    FILE *btc;

    if((btc=fopen("BTC.csv", "r")) == NULL  )
    {
        printf("not found btc\n");
        exit(-1);
    }


    long int a=0;

    char linha[256];
    char *token = NULL;

    while (fgets(linha, sizeof(linha), btc) != 0)
    { 
            a++;
    }

    vetor *v;

    v=(vetor*)malloc(a*sizeof(vetor));

    char linha2[256];

    while (fgets(linha2, sizeof(linha2), btc) != 0)
    {
        for(int i=0;i<a;i++)
        {
            fscanf(btc,"%[^,]s",v[i].date);
            fscanf(btc,"%d[^,]",&v[i].value);
            fseek(btc, +1, SEEK_CUR);
        }
    }

    fclose(btc);    
    return 0;
}
  • It would not be equivalent to this question?

  • Also... note that you are reading the 2x file. On the second pass you should go back to the beginning of the file.. try to use the function rewind(btc) to return the file to its initial state before the second while.

  • Friend, I asked a similar question yesterday, and I got a good answer, which can help you there too, since there are only two columns. Parsing columns of numbers from a CSV file in C

1 answer

0

In its vector structure you define two pointers: a char pointer (date) and another pointer to long int (value). To effectively store the read values you need to allocate the required space and have each of these pointers point to the respective memory space.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.