In this article we will discuss, how to create a class to write data to a CSV File.

What is a CSV File ?

A CSV file is a kind of flat file used to store the data. In this each row contains data separated by comma.
For example,

Creating a CSVWriter Class to store Data to CSV File

Let’s create a class CSVWriter that provides API to store data to CSV File

Its constructor accepts the filename as an argument. It also provide a template member function that accepts a range as an argument and store all of them in last row, separated by comma i.e.

As this function expects a range, we can pass iterator of any container like vector/set or an array.

Let’s create an object of CSVWriter class i.e.

Write a Vector of strings to CSV file using CSVWriter class

Write a Set to CSV file using CSVWriter class

Write an Array to CSV file using CSVWriter class

Check complete example as follows,

It generates a file example.csv with following contents,

To compile the above code on Linux, use following command,

g++ –std=c++11 example.cpp

Click Here to Subscribe for more Articles / Tutorials like this.