如何在 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

更新于: 2020 年 2 月 11 日

3K+ 浏览

开启你的 职业生涯

完成课程,获得认证。

开始
广告
© . All rights reserved.