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

Asked

Viewed 945 times

0

I’m having difficulty assigning read values of a file in csv format to a 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 is like this:

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

function performing csv file reading:

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 35 position vector and I intend to assign the values before each point and comma, for example:

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

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

1 answer

1

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

The file was opened with the fopen, I think using the 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);
}
  • @Jjoao. I really thought about putting "read the characters", but the command should read anything before the ";" regardless of what is there, so I’m using the term "bytes" instead of "characters".

Browser other questions tagged

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