Computer >> Máy Tính >  >> Lập trình >> C ++

Làm cách nào để đọc và phân tích cú pháp tệp CSV trong C ++?


Bạn thực sự nên sử dụng thư viện để phân tích cú pháp tệp CSV trong C ++ vì có nhiều trường hợp bạn có thể bỏ lỡ nếu bạn tự đọc tệp. Thư viện tăng cường cho C ++ cung cấp một bộ công cụ thực sự tốt để đọc tệp CSV. Ví dụ,

ví dụ

#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;
   }
}

đầu ra

Điều này sẽ đưa ra kết quả -

hello
from
here

Một cách khác là sử dụng dấu phân cách để tách một dòng và đưa nó vào một mảng -

Ví dụ

Một cách khác là cung cấp dấu phân cách tùy chỉnh để tách chuỗi bằng cách sử dụng hàm 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;
   }
}

Đầu ra

Điều này sẽ đưa ra kết quả -

hello
from
here