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
অন্য উপায় হল একটি রেখাকে বিভক্ত করার জন্য একটি বিভাজক ব্যবহার করা এবং এটিকে একটি অ্যারেতে নেওয়া -
উদাহরণ
অন্য উপায় হল গেটলাইন ফাংশন ব্যবহার করে স্ট্রিংকে বিভক্ত করার জন্য একটি কাস্টম ডিলিমিটার প্রদান করা -
#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