How do you assign data to a struct by reading from a CSV file?

0

I am having difficulty assigning read values from a file in csv format to one struct, my file has the following structure:

1;República Checa;156.9
2;Irlanda;131.1
3;Alemanha;115.8
4;Austrália;109.9
5;Áustria;108.3

And my code looks like this:

struct Nodo{
      int classificacao;
      char pais[30];
      float consumo;
};

function that reads the csv file:

void leArquivoDeDados() {
 int length;
 char * buffer;

 struct Nodo nodo[35];

 ifstream is;
 is.open ("dados.csv", ios::in);

 is.seekg (0, ios::end);
 length = is.tellg();
 is.seekg (0, ios::beg);

 if (is.is_open())
 {
    int n = 0;
    buffer = new char[length];
    is.read(buffer,length);

   if (length > 0)
   {
      while(n < length) //isso substitue o ";" para um espaço
      {
         n++;
         if (buffer[n] == ';') buffer[n] = '\t';
      }

      printf("%s", buffer);
      getch();
      delete []buffer;
   }
 }
 else {
   printf("Arquivo não foi aberto");
   getch();
}

  is.close();
}

I am declaring my struct as a vector of 35 positions and I want to assign the values before each semicolon, for example:

Nodo.classificacao = 1;
Nodo.pais = 'Irlanda';
Nodo.consumo = 156.9;

My function is able to write to the terminal my file, but I do not know how to accomplish this assignment in the above example at the time of reading the file, I am replacing the ";" by spaces only to visualize better in the terminal.

    
asked by anonymous 23.04.2016 / 05:52

1 answer

1

I think the best command to collect data from files and play directly on variables is fscanf , post it is possible to determine the input format.

The file was opened with fopen , I think using ifstream will not have the same effect.

FILE *f = fopen("file.txt","r");

int x;
for(x=0;x<35/*tamanho do vetor*/;x++){
    /* %d - lê um inteiro
       %30[^;] - lê os bytes até o caractere ';'
       %f - lê um float
    */
    fscanf(f,"%d;%30[^;];%f\n", &nodo[x].classificacao, nodo[x].pais, &nodo[x].consumo); // lê os dados e armazena em nodo
    printf("%d - %s - %f\n", n[x].classificacao, n[x].pais, n[x].consumo);
}
    
23.04.2016 / 06:32