Read from file txt to vector of char

1

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

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

And so on, with a total of 500 cpfs. I'm trying to read each one and put char cpf[12] (because each one has 12 characters counting - ), however when printing 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 it was the same. So I'd 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 afterwards.

    
asked by anonymous 04.10.2018 / 19:45

1 answer

1

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

To correct the following is enough:

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] = '
#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
    }
}
'; //coloca o terminador no fim da string

Just as I said in the commentary C ++ provides you with simpler ways of reading files as well as storing strings, which precisely avoids this kind of detail that is easy to go unnoticed.

In c ++ to read all cpfs you can do this:

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] = '
#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
    }
}
'; //coloca o terminador no fim da string

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

    
04.10.2018 / 20:54