如何在 C++ 中讀取和解析 CSV 檔案?
你真正應該使用一個庫來解析 C++ 中的 CSV 檔案,因為如果你自己讀取檔案的話可能會遺漏很多情況。針對 C++ 的 boost 庫提供了一套非常好用的工具來讀取 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
廣告