Problem reading file

Asked

Viewed 59 times

0

I’m writing a code in C++ and I need to read a distance file that was calculated in another algorithm made in C.

This file looks something like this:

100 n (natural number) 0.0000 58.25646 7.1556 N5.1564 0.0000 44.00000... -> a matrix of floats

Follow the code of the part that reads the file:

int main(){
    srand(time(NULL));

    FILE *arv;
    arv = fopen("distancias_oliver30.txt", "r");

    fscanf(arv,"%d", &N_geracoes);



    float distancias[N_cidades][N_cidades];
    float feromonio[N_cidades][N_cidades];

    int i, j, k;
    for (i = 0; i < N_cidades; i++){
        for (j = 0; j < N_cidades; j++){
            fscanf(arv,"%d",&distancias[i][j]);

    }


    fclose(arv);
    ...

The problem is that the first natural number he reads correctly, but the distance he reads the first element correctly and the rest he puts a weird negative number (-107374176) instead of 58.25646, 5.1564...

Does anyone know how to solve?

1 answer

2


Assuming this statement:

float distancias[N_cidades][N_cidades];

That is wrong:

fscanf(arv,"%d",&distancias[i][j]); // ERRADO!

This is the right way to read floats:

fscanf(arv,"%f",&distancias[i][j]); // CERTO :)
  • 1

    Puts... that stupid mistake. Thank you very much :))))))))))))))

Browser other questions tagged

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