I am doing a project for an electronic ballot box, and for this 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 not determine the end of the first row, and the index continues to be 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 the getline () of the first row is incremented. When a desired column is found, the position of that column is saved, so when the counter is initialized i = 1 on the next line some action is performed on the desired column.
The code I wrote is the one 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 quotation mark, "" SG_PARTIDO "". When I removed the first and last character, before the comparison, this condition becomes true, but I continue with the problem of not knowing when the first line ends.
The code that removes 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 would appreciate it 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: link