Segmentation fault 11 when reading a CSV file in C++

Asked

Viewed 30 times

0

Good night, you guys! Next, I made this code from a response from here of the stack overflow and it’s giving Segmentation fault 11 on the last line of the file, someone help me solve, please! This is my code:

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

void read_archive(const char *in) {
ifstream file(in);
string buffer;
vector <vector<string> > linhas; //Vetor de vetor para todas as linhas
while(!file.eof()) {
    getline(file, buffer);
    stringstream ss(buffer);

    vector<string> linha;
    while(getline(ss, buffer, ';')) {
        linha.push_back(buffer);

    }
    linhas.push_back(linha);
}

    vector<unsigned long> ColunasRelevantes; //ColunasRelevantes[X];

    for(size_t i = 0; i < linhas[0].size(); i++) {
        string nomeColunas = linhas[0][i].substr(1, linhas[0][i].size() - 2); //Tirar as 2 aspas
        if(nomeColunas == "SG_PARTIDO") {
            ColunasRelevantes.push_back(i);
        }
    }

    for(size_t i = 0; i < linhas.size(); i++) {
        for(size_t j = 0; j < ColunasRelevantes.size(); j++) {
            unsigned long Coluna = ColunasRelevantes[j];
            string texto = linhas[i][Coluna].substr(1, linhas[i][Coluna].size() - 2);
            cout << texto << "\t";
        }
        cout << endl;
    }
}
int main () {

    read_archive("consulta_cand_2018_BR.csv");
    return 0;
}
  • Without having a sense of what content the file has, it’s hard to say what might not be right. But according to the reading done in the code you have, there can be no blank lines in the file, so make sure that the last line has no blank lines

  • The link to the csv I am using is this: https://gitlab.com/oofga/eps/eps_2018_2/ep1/raw/master/data/consulta_cand_2018_BR.csv?inline=false

  • As I started to warn, the file has one last blank line, line 28.

No answers

Browser other questions tagged

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