आपको C++ में CSV फाइलों को पार्स करने के लिए वास्तव में एक लाइब्रेरी का उपयोग करना चाहिए क्योंकि ऐसे कई मामले हैं जिन्हें आप अपने आप फाइल पढ़ते समय मिस कर सकते हैं। C++ के लिए बूस्ट लाइब्रेरी CSV फाइलों को पढ़ने के लिए वास्तव में अच्छे टूल्स का एक सेट प्रदान करती है। उदाहरण के लिए,
उदाहरण
#include<iostream> vector<string> parseCSVLine(string line){ using namespace boost; std::vector<std::string> vec; // इनपुट स्ट्रिंग को टोकनाइज़ करता है 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 = ','; // विभाजित करने के लिए डिलीमीटर परिभाषित करें while (std::getline(str_strm, tmp, delim)) { // tmp के लिए उचित चेक यहां प्रदान करें जैसे खाली है या नहीं // !, ., ?, आदि जैसे सिंबल्स को भी स्ट्रिप करें। // अंत में पुश करें। words.push_back(tmp); } for(auto it = words.begin(); it != words.end(); it++) { std::cout << *it << std::endl; } }
आउटपुट
यह आउटपुट देगा:
hello from here