Read from a txt file using fscanf using vector

0

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 struct car, I have already gotten it with that record but for some reason I do not understand the program, when it loads from the file, it bursts.

The file, if it is 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!

    
asked by anonymous 16.03.2017 / 21:24

1 answer

0

I think you should use the fscanf function itself as a condition, because at 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;
}

But in c ++ the correct thing is to use streams to read from files. An advice... Do not use the word auto since it is part of the c ++ 11 pattern and is a reserved word for the language.

    
19.03.2017 / 23:11