How to Parse a CSV File
c++11
files
intermediate
Related: How to read a file
A CSV file is a file with comma separated values. CSV files are useful because they can represent tabular data very simply. To parse a CSV file in C++ we’ll use the streams library from the Standard Library.
To open a file for reading in C++ we use std::ifstream
(input file stream).
We’ll read the file line by line, parsing each line with a std::istringstream
(input string stream).
The input file we’ll parse as an example is:
name,distance,radius Mercury,0.4,4879.4 Venus,0.7,6051.8 Earth,1.0,6371.0 Mars,1.5,3389.5 Jupiter,5.2,69911 Saturn,9.5,58232 Uranus,19.2,25362 Neptune,30.1,24622
#include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <vector> int main() { std::string filename{"csv_file.txt"}; std::ifstream input{filename}; if (!input.is_open()) { std::cerr << "Couldn't read file: " << filename << "\n"; return 1; } std::vector<std::vector<std::string>> csvRows; for (std::string line; std::getline(input, line);) { std::istringstream ss(std::move(line)); std::vector<std::string> row; if (!csvRows.empty()) { // We expect each row to be as big as the first row row.reserve(csvRows.front().size()); } // std::getline can split on other characters, here we use ',' for (std::string value; std::getline(ss, value, ',');) { row.push_back(std::move(value)); } csvRows.push_back(std::move(row)); } // Print out our table for (const std::vector<std::string>& row : csvRows) { for (const std::string& value : row) { std::cout << std::setw(10) << value; } std::cout << "\n"; } }
Of course, you may want to interpret your data as types other than just strings. For that we’ll need the “string to” family of functions such as string to int.