Read from a txt file via fscanf using vector

Asked

Viewed 593 times

1

I have the following

while(!feof(f)){
        (*ptr).push_back(carro());
        fscanf (f, "%d", (*ptr)[add].id);
        fscanf (f, "%s", (*ptr)[add].marca);
        add++;
}

Where *ptr is &vector, a vector of a car struct, I have already managed to save but for some reason I do not understand the program, when it loads the file, it breaks.

The file, if important, contains:

1 VW
2 Seat
3 Audi

And the struct is as follows:

typedef struct Auto{

   int id;
   char marca[50];

}carro;

Thank you!

1 answer

0


I think you should use the fscanf function itself as a condition, because when reaching the end of the file it returns EOF.

#include <iostream>
#include <vector>
using namespace std;

struct Automovil {
    int id;
    char marca[50];

};

void lerArquivo(vector<Automovil> &lista){
    FILE *f = fopen("autos.txt", "r");
    Automovil dados;
    while ( fscanf(f,"%d %s", &dados.id, dados.marca) != EOF ) {
        lista.push_back( dados );
    }
    fclose(f);

}

int main () {
    vector<Automovil> lista;

    lerArquivo(lista);

    for (unsigned int i = 0; i<lista.size() ; i++ ) {
        cout << "vetor[" << i << "] = ID: " << lista[i].id << ", Marca: " << lista[i].marca << endl;   
    }


    cin.ignore();
    return 0;
}

However in c++ the correct is to use streams to read from files. A word of advice... Do not use the word auto since it is part of the c++11 standard and is a reserved word of the language.

Browser other questions tagged

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