आपको वास्तव में 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