How to read and parse CSV files in C++?

C++Server Side ProgrammingProgramming

You should really be using a library to parsing CSV files in C++ as there are many cases that you can miss if you read files on your own. The boost library for C++ provides a really nice set of tools for reading CSV files. For example,

example

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

output

This will give the output −

hello
from
here

Another way is to use a delimiter to split a line and take it in an array −

Example

Another way is to provide a custom delimiter to split the string by using the getline function −

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

Output

This will give the output −

hello
from
here
raja
Published on 28-Feb-2018 11:47:55
Advertisements