2012-05-15 18 views
0

我想知道如何從Excel文件中讀取信息(保存爲.csv),然後使用C++將其打印到另一個文件中。如何從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

[C++中的CSV解析器]的可能重複(http://stackoverflow.com/questions/1120140/csv-parser-in-c) – xan

+0

我覺得我每天都會看到這個問題的不同版本。 – luke

+0

重複以下問題:http://stackoverflow.com/questions/1120140/csv-parser-in-c –

回答

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++; 
    } 

我希望你會滿意這個;)

+0

非常感謝Thierry。你知道我怎麼打印只有3列的信息。例如,3,4和5. – Adrian

+0

嗨艾德里安,你能告訴我,如果這是好的話。謝謝。 – ThierryT

+0

嗨蒂埃裏,抱歉沒有回答...是的,它是完美的。非常感謝;) – Adrian

0
#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; 
      } 
     } 
    } 

}