2013-04-08 339 views
1

我有一个可以成功读取CSV文件的程序。所述CSV文件是由3列分隔的列表。每列之间有一个逗号。例如使用getLine在C++中读取CSV文件中的分隔列

线1 ---艺术家,流派,歌曲 线2 ---迈克尔·杰克逊,流行音乐,惊悚片

等。我想要我的节目要做的是读第一行,并把艺术家,流派和歌曲作为选项打印出来。例如

“选择选项” 1.艺术家 2.体裁 3.宋

,然后当他们选择一个选项,那么就说明他们要么所有的艺术家,歌曲,或CSV流派文件。

到目前为止,我有我的程序读取CSV并将每行放入向量中。这是到目前为止我的代码...

#include <iostream> 
#include <sstream> 
#include <string> 
#include <fstream> 
#include <vector> 
using namespace std; 
int main() 
{ 
    ifstream infile("music_list.csv"); 
    string line = ""; 
    vector<string> all_words; 
    cout << "Hello"; 
    while (getline(infile, line)) 
    { 
     stringstream strstr(line); 
     string word = ""; 
     while (getline(strstr,word, ',')) 
     { 
      all_words.push_back(word); 
     } 

     for (unsigned i = 0; i < all_words.size(); i++) 
     { 
      cout << all_words.at(i)<< "\n"; 
     } 

    } 
    system("pause"); 
    return 0; 
} 

我只是遇到问题搞清楚如何把它读的第一线,每根弦在已经用逗号分隔,并具有第一线分开然后作为选项输出给用户。因此,本质上,我可以在CSV文件中将艺术家,流派,歌曲更改为开胃菜,菜肴,饮料等。

+0

相关:http://stackoverflow.com/q/236129/951890 – 2013-04-08 03:45:03

回答

1

首先,您必须读取csv文件并将行存储在向量中,您可以使用此函数来完成此操作。

vector<string> readCsvFileContent(const string file) 
{ 
     vector<string> buffer; 
     ifstream configFile; 
     configFile.exceptions(ifstream::badbit); 
     try 
     { 
      configFile.open(file.c_str(),ifstream::in); 
      if(configFile.is_open()) 
      { 
       string line;     
       while (getline(configFile,line)) 
       { 
        buffer.push_back(line); 
       } 
       configFile.close(); 
      }   
     } 
     catch (ifstream::failure e){    
      throw e; 
     } 
     return buffer; 
} 

然后将每一行条目分割为2D向量。对于您可以使用此功能

vector<vector<string>> processCsvList(vector<string> csvList) 
{ 
    #define SINGER_CONFIG_COUNT 3 //number of comma separated data suppose to be in one line. 
    #define DELIMITED_CHAR "," 
    #define EMPTY_STRING ""; 

    vector<vector<string>> tempList; 
    string configCell =""; 
    for(vector<string>::iterator it = csvList.begin(); it != csvList.end(); ++it) 
    { 
     if(*it == EMPTY_STRING) 
     { 
      continue; 
     } 
     stringstream configLine(*it); 
     vector<string> tempDevice; 
     for(int i=0; i<SINGER_CONFIG_COUNT; i++) 
     { 
      if(getline(configLine,configCell,DELIMITED_CHAR)) 
      {    
       tempDevice.push_back(configCell); 
      }else 
      { 
      tempDevice.push_back(EMPTY_STRING); 
      } 
     } 
     tempList.push_back(tempDevice); 
    } 
    return tempList; 
} 

我还没有尝试编译这些功能的,因为我没有环境,所以在这里做。但我认为这将有助于思考方向。

现在您的数据在像excell工作表的2D矢量中。所以你可以通过内部向量的索引来访问。

0

您可以创建一个std::map<string,vector<string>>,让你可以再从2号线的CSV文件中的每一列存储起在地图作为一个字符串矢量,通过出现在列的CSV文件的第1行中的文本键。

然后,你可以通过该std::map的钥匙,这是方便地存储在字母顺序迭代呈现的字段的名称。

在CSV文件的第一行中阅读的任务可以通过您已有的代码执行,也可以通过考虑在全功能CSV文件中找到的引用字段等的更复杂的代码执行。