কম্পিউটার টিউটোরিয়াল

C++-এ CSV ফাইল পড়া এবং পার্স করা (Parse CSV Files)

CSV পার্সিং ম্যানুয়ালি করা জটিল (কোটেড ফিল্ড, এসকেপড কমা, নিউলাইন ইন ফিল্ড)। লাইব্রেরি ব্যবহার করা ভালো।

পদ্ধতি ১: Boost.Tokenizer (এসকেপ হ্যান্ডলিংসহ)

#include <iostream>
#include <vector>
#include <string>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;

vector<string> parseCSVLine(string line) {
    vector<string> vec;
    tokenizer<escaped_list_separator<char>> tk(line, escaped_list_separator<char>('\\', ',', '\"'));
    for(auto it = tk.begin(); it != tk.end(); ++it)
        vec.push_back(*it);
    return vec;
}

int main() {
    string line = "hello,from,here";
    auto words = parseCSVLine(line);
    for(auto &w : words) cout << w << endl;
}

আউটপুট

hello
from
here

পদ্ধতি ২: সিম্পল getline (কমা ডিলিমিটার, নো এসকেপ হ্যান্ডলিং)

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;

int main() {
    stringstream str_strm("hello,from,here");
    string tmp;
    vector<string> words;
    char delim = ',';
    while(getline(str_strm, tmp, delim))
        words.push_back(tmp);
    for(auto &w : words) cout << w << endl;
}

সুপারিশ: প্রোডাকশন কোডে Boost.Spirit, csv-parser (header-only), বা rapidcsv ব্যবহার করুন। C++23-এ std::csv প্রস্তাবিত।

  1. C++-এ int কে string-এ রূপান্তর (Integer to String)

  2. C++-এ রিলেশনাল অপারেটর (==) এবং std::string::compare() এর পার্থক্য

  3. পাইথনে ইউনিকোড (UTF-8) ফাইল পড়া এবং লেখা কীভাবে করবেন?

  4. রুবিতে সহজে CSV ফাইল পড়ুন এবং পার্স করুন