Read from txt file to char vector

Asked

Viewed 1,293 times

1

I have a file dados.txt with (fictitious) Cpfs in the following format:

382031758-71
647900189-01
460754503-73
696170135-72

And so on, being in total 500 cpfs. I’m trying to read each and put in char cpf[12] (because each one has 12 characters counting the -), but when printing are printed three strange characters type @ýý

int main(){

//abre o arquivo em modo leitura
FILE *dados = fopen("dados.txt", "r");

char cpf[12]; 

fseek(dados, 0, SEEK_SET); //vai para o inicio do arquivo
//fgets(cpf, 100, dados); //pega 12 caracteres 

for(int i = 0; i < 12; i++){
    cpf[i] = fgetc(dados);
}

printf("%s\n", cpf);

fclose(dados);
}

I also tried with fscanf(dados, "%s\n", cpf); but gave in anyway. So I would like to understand how to read this data in this way. I want to store in a variable because I need to use this to test a hash function later.

  • I believe it is because your vector is not considering the end of the string, change char cpf[12] for char cpf[13]

  • that’s not it, even if it changes to Cpf[100] continues like this

  • 2

    C or C++ ? The code you have is C but marked the tag C++ and C++ has much simpler ways to read file information, as well as to store in variables.

  • whatever, it can be in c++

1 answer

1


The reading that is being done not only does not allocate space for the terminator, but also does not place it. For this reason when trying to show the value in the console it picks up other values that are in the memory that follows where the vector of char was allocated.

To correct just the following:

int main() {
    FILE *dados = fopen("dados.txt", "r");

    char cpf[13]; //13 em vez de 12 para guardar tambem o terminador
    fseek(dados, 0, SEEK_SET);

    for(int i = 0; i < 12; i++) {
        cpf[i] = fgetc(dados);
    }
    cpf[12] = '\0'; //coloca o terminador no fim da string

Just as C++ said in comment, it provides you with simpler ways to read files as well as store strings, which precisely avoids this kind of details that are easy to go unnoticed.

In c++ to read all cpfs can do so:

#include <iostream>
#include <fstream>

int main() {
    std::ifstream dados("dados.txt");
    std::string cpf;
    while (std::getline(dados, cpf)){ //ler cada cpf até ao fim
        std::cout << cpf << std::endl; //usar o cpf
    }
}

I used the ifstream to operate on the file as input data, and I read it line by line at the expense of getline.

Browser other questions tagged

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