In this post we are going to see how to parse CSV with C++ without any ready-made library for this and use some modern tools and resources, such as:
CSV means “Comma-separated values”. In short, they are text files used to store data as a “database”.
The RFC standard describes data as comma-separated, however, there are variants that inform in the first line the indication that which separator(sep=;
, sep=|
) will be used in the document, in fact, Microsoft Excel exports data to CSV with this variant.
To create our code we will need an example of CSV and for that we will use this example:
file.csv
The code below uses strsep
instead of strtok as we saw in this article, to notice the difference I suggest replacing those with strsep(&buf, delim)
by strtok(NULL, delim)
and note that the line that has empty data will have incorrect data.
main.cpp
CMakeLists.txt
file
tree cppsv
Compiling and running:
Very easy and a nice C++ exercise. Of course, you can still improve, for example, add separator checking to be compatible with the model generated by Excel. And even create a ready-made library. Another thing is that some CSV files may have the data protected by double quotes, so you can replace them with empty and so on.
If you want to see the whole process step by step in video form, watch the content below, remembering that the video is in Portuguese, but the content is language independent, however, you can still use Youtube’s automatic translation.