我想知道如何从Excel文件(保存为.csv)中读取信息,然后使用C ++将其打印到另一个文件中。
输入文件将数据分成列。每列的第一行是列的标签。比如这个:
|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
所以从这张表中,我想提取第3,4和5列(仅当有信息时,所以第2,3和6行)并打印信息 进入另一个csv文件,例如:
|Column3|Column4|Column5|
|int3.2 |char4.2|bool5.2|
|int3.3 |char4.3|bool5.3|
|int3.6 |char4.6|bool5.6|
答案 0 :(得分:3)
strtok是这样做的标准功能。
#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;
}
欢迎你! 如果你想对某些列进行过滤,那么,由于strtok不接受列号的参数,你将不得不使用条件语句,如if,switch(对于特定的处理,取决于列等)
对于你的例子:
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++;
}
或使用开关,允许对每列进行特定处理:
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++;
}
我希望你会对此感到高兴;)
答案 1 :(得分:1)
#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;
}
}
}
}