How can we not access it with pointers?

Asked

Viewed 63 times

2

I have a code where I create and then read a file .dat with information from sales records, such as date, time, price, etc. I can do a search by date, for example, and generate another file .dat only with the purchase records of that date, however, when I use the read function to read this new generated file it cannot access the information that is in the record, the program tops, as if it were some improper access of the pointer, as I see.

header. h


class RegistroVenda{    // classe com os dados que vou salvar no arquivo
public:
    string data, hora, cidade, etc.... ;
};

file.cpp


RegistroVenda * v = new RegistroVenda(); // uso v para acessar a classe, deixo aqui em cima pra ficar global

void Leitura(string nome_arquivo){ // na primeira chamada da função tudo vai funcionar
    
    fstream arquivo(nome_arquivo, ios::in|ios::binary); ... ok

    //verifico se abriu certo... ok
    //calculo tamanho do arquivo... ok

    for(int i=0; i<tamanho_arquivo; i++){

        /* .read() ta lendo um bloco de dados e passando pra v, que é global,
           então ele deveria acessar os atributos da classe corretamente */

        arquivo.read( (char*)v, sizeof(RegistroVenda) ); 

        cout << "cidade = " << v->cidade << endl; // só que quando tento acessar a cidade por exemplo, da erro
    }
}

The first time I run the program it will read a file .txt, will save the data to a file .dat, then I can search this file .dat and the search result I saved in another file .dat. So far everything works beauty.

Then I’ll call the same function you read before (and it worked) to read the search result, only that’s where the program tops. When it’s time to access attributes ( v->cidade for example) it tops.

Why v can’t access the contents of the variables the second time I rotate the function? It seems that, when rotating a second time, he loses the reference of something and ends up making an improper access.

  • Post an entire, compileable program. Post an example of the txt file to have a minimum playable problem for anyone who wants to help. Don’t use global variables. Never. Use a Sale class and the operations you need. Work with memory sales if possible, using one of the many containers the language offers. And only record at the end.

1 answer

0


The problem was revolving around the variables of the type String. The solution I found was the following:

1º) Change the type of the structure variables

class RegistroVenda
{
public:
    float preco;
    char nome[30]; // troca string por isso
};

2º) Make a copy of the type string for a guy char[] using strcpy() and c_str()

char linha[TAM_LINHA];
string s;

while(!arquivo.eof()){
        RegistroVenda r;
        arquivo.getline(linha,TAM_LINHA);
        r.preco = atof(strtok(linha,";")); // atof() convert pra float

        s = strtok(NULL,";");    
        strcpy(r.nome,s.c_str()); // copia string de 's' e passa pra 'nome'
}

Then next, strtok() will read a string in my linha up to the delimiter ;, that I use to separate the data from the record. The second data from my record is the nome, but I can’t pass linha as parameter again, if not it will come back from the beginning of the line, and this is not what I want. I want to continue on the same line, then step NULL as parameter and say what is the next delimiter.

All right, now I do s receive a string of characters, continuing on the same line as read and is stored in linha. This string is the name, and then I make a copy of s for nome.

Ready, done that the file .bin generated with records can be read normally in separate executions. I cannot explain why variables of type string went wrong and kind of char[] worked. If anyone can explain this better, I’m grateful.

  • Obs: char vector is very sensitive, in the sense that it gives enough problem when using. I went to use it in another exercise and just changing the size of the char vector it generated different answers. If you have a problem with a variable char vet[xx], test change vector size.

Browser other questions tagged

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