如何在 C++ 中讀取和解析 CSV 檔案?


在 C++ 中讀取檔案時,你可能會遺漏許多情況,因此你應使用一個庫來解析 CSV 檔案。C++ 的助推庫提供了一組非常實用的工具來讀取 CSV 檔案。例如:

示例

#include<iostream>
vector<string> parseCSVLine(string line){
   using namespace boost;

   std::vector<std::string> vec;

   // Tokenizes the input string
   tokenizer<escaped_list_separator<char> > tk(line, escaped_list_separator<char>
   ('\', ',', '\"'));
   for (auto i = tk.begin();  i!=tk.end();  ++i)
   vec.push_back(*i);

   return vec;
}

int main() {
   std::string line = "hello,from,here";
   auto words = parseCSVLine(line);
   for(auto it = words.begin(); it != words.end(); it++) {
      std::cout << *it << std::endl;
   }
}

輸出

將輸出 −

hello
from
here

另一種方法是使用分隔符拆分行,並將其放入一個數組中 −

示例

另一種方法是使用 getline 函式提供自定義分隔符來拆分字串 −

#include <vector>
#include <string>
#include <sstream>

using namespace std;

int main() {
   std::stringstream str_strm("hello,from,here");
   std::string tmp;
   vector<string> words;
   char delim = ','; // Ddefine the delimiter to split by

   while (std::getline(str_strm, tmp, delim)) {
      // Provide proper checks here for tmp like if empty
      // Also strip down symbols like !, ., ?, etc.
      // Finally push it.
      words.push_back(tmp);
   }

   for(auto it = words.begin(); it != words.end(); it++) {
      std::cout << *it << std::endl;
   }
}

輸出

將輸出 −

hello
from
here

更新時間: 2020-02-11

3 千+ 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告