3
I am doing a design of an electronic ballot box, and for that I need to read a csv file where there is information about each candidate.
As this csv file has a lot of information that is not relevant, I decide to use only certain columns of the csv file, for example: NM_CANDIDATO, NM_PARTIDO, ...
The solution I thought was to start a counter to save the "index" of the desired columns, but I can’t determine the end of the first line, and the index keeps being incremented with all the data.
"DT_GERACAO"; "SG_PARTIDO" ; "HH_GERACAO"
"03/09/2018"; "DC" ; "08:01:43"
"03/09/2018"; "MDB" ; "08:01:43"
"03/09/2018"; "PODE" ; "08:01:43"
In this example, only the column SG_PARTIDO interests me. Thus, a counter i is initialized i=1 and during getline() of the first line is incremented. When a desired column is found, the position of that column is saved, so that when the counter is initialized i=1 in the next row some action is performed in the desired column.
The code I wrote is this below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("presidentes.csv");
if(!file.is_open())
{
cout<<"Erro! Não foi possível abrir esse arquvio"<<'\n';
}
string buffer;
int i=1 p_SG_PARTIDO = 0;
while(!file.eof())
{
getline(file, buffer, ';');
if(buffer == "SG_PARTIDO" || i == p_SG_PARTIDO)
{
p_SG_PARTIDO = i;
cout << buffer;
}
i++;
if(buffer == "\n") i=1;
}
file.close();
return 0;
}
This buffer condition is never true. I suspect the reason is a double quote, ""SG_PARTIDO"". When I removed the first and last character, before the comparison, that condition becomes true, but I still have the problem of not knowing when the first line ends.
The code that I remove the character is this below:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream file("presidentes.csv");
if(!file.is_open())
{
cout<<"Erro! Não foi possível abrir esse arquvio"<<'\n';
}
string buffer;
int i=1;
int p_ds_cargo = 0;
while(!file.eof())
{
getline(file, buffer, ';');
if(buffer[0]=='"') // remover """"
{
buffer.erase(0,1);
buffer.erase(buffer.size() - 1);
}
if(buffer == "DT_GERACAO")
{
p_ds_cargo = i;
cout << buffer << endl;
}
if(buffer == "\n") i = 1;
i++;
}
file.close();
return 0;
}
I appreciate if anyone knows an easier way to read only specific columns in a csv file.
The link to the csv I’m using is this: https://gitlab.com/oofga/eps/eps_2018_2/ep1/raw/master/data/consulta_cand_2018_BR.csv?inline=false
I really liked this new way of reading the relevant columns!! Thank you very much, you opened my mind!!
– Durval Carvalho
@Durvalcarvalho No problem we’re here to help :)
– Isac