Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

จะอ่านและแยกวิเคราะห์ไฟล์ CSV ใน C ++ ได้อย่างไร


คุณควรใช้ไลบรารี่เพื่อแยกวิเคราะห์ไฟล์ CSV ใน C++ เนื่องจากมีหลายกรณีที่คุณอาจพลาดหากคุณอ่านไฟล์ด้วยตัวเอง ไลบรารีบูสต์สำหรับ 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