Reputation: 33
I would like to know how to read information from an Excel file (saved as .csv) for then printing it into another file, using C++.
The input file has the data separated into columns. The first line of each column is the label of the column. Such as this:
|Column1|Column2|Column3|Column4|Column5|Column6
|char1.1|char2.1| | | |char6.1
|char1.2|char2.2|int3.2 |char4.2|bool5.2|char6.2
|char1.3|char2.3|int3.3 |char4.3|bool5.3|char6.3
|char1.4|char2.4| | | |char6.4
|char1.5|char2.5| | | |char6.5
|char1.6|char2.6|int3.6 |char4.6|bool5.6|char6.6
So from this table, I would like to extract the columns 3, 4 and 5 (only when there is information, so lines 2,3 and 6) and print the information into another csv file, such as this:
|Column3|Column4|Column5|
|int3.2 |char4.2|bool5.2|
|int3.3 |char4.3|bool5.3|
|int3.6 |char4.6|bool5.6|
Upvotes: 3
Views: 10240
Reputation: 21
#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <sstream>
int main(int argc, char* argv[])
{
std::string csv_File_name = argv[1];
std::ifstream data(csv_File_name);
int row_count =0 ;
std::string line;
while(std::getline(data,line))
{
row_count +=1;
std::stringstream lineStream(line);
std::string cell;
int column_count = 0 ;
while(std::getline(lineStream,cell,','))
{
column_count+=1;
// You have a cell!!!!
if ( column_count == 3 || column_count == 4 || column_count == 5){
std::cout << cell <<" row " << row_count << " column " << column_count<< std::endl;
}
}
}
}
Upvotes: 1
Reputation: 191
strtok is standard function to do that.
#include <stdio.h>
#include <string.h>
int main ()
{
// Read the file ----------
FILE* fp = fopen("toto.csv", "rb");
if (fp == NULL) return 0;
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
char *pData = new char[size + 1];
fread(pData, sizeof(char), size, fp);
fclose(fp);
// Read the file ----------
// Parse the file content ----------
char* pch;
pch = strtok (pData, "|");
while (pch != NULL)
{
printf ("%s\n", pch);
pch = strtok (NULL, "|");
}
// Parse the file content ----------
return 0;
}
You're welcome ! If you want to filter on some columns, then, since strtok doesn't take in argument the column number, you will have to use a conditional statement like if, switch (for a specific treatment depending column etc)
For you example:
char* pch;
pch = strtok (pData, "|");
int iCpt = 1;
while (pch != NULL)
{
if (iCpt == 3 || iCpt == 4 || iCpt == 5)
{
printf ("%s\n", pch);
}
pch = strtok (NULL, "|");
iCpt++;
}
Or using switch, allowing a specific treatment on each column:
char* pch;
pch = strtok (pData, "|");
int iCpt = 1;
while (pch != NULL)
{
switch(iCpt)
{
case 3:
case 4:
case 5: printf ("%s\n", pch);
break;
default: // Nothing;
}
pch = strtok (NULL, "|");
iCpt++;
}
I hope you will happy with this ;)
Upvotes: 3