如何在 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 千+ 次浏览

开启你的职业

通过完成课程获得认证

开始
广告
© . All rights reserved.