How to Read CSV File in C++: Simple Guide with Example
To read a CSV file in C++, use
std::ifstream to open the file and std::getline to read each line. Then, use std::stringstream to split each line by commas and extract the values.Syntax
Here is the basic syntax to read a CSV file line by line and split each line by commas:
std::ifstream file(filename);opens the CSV file.std::string line;stores each line read from the file.std::getline(file, line);reads one line at a time.std::stringstream ss(line);allows splitting the line by commas.std::getline(ss, cell, ',');extracts each cell separated by commas.
cpp
std::ifstream file("filename.csv"); std::string line; while (std::getline(file, line)) { std::stringstream ss(line); std::string cell; while (std::getline(ss, cell, ',')) { // process each cell } }
Example
This example reads a CSV file named data.csv and prints each cell to the console. It shows how to open the file, read lines, split by commas, and handle the data.
cpp
#include <iostream> #include <fstream> #include <sstream> #include <string> int main() { std::ifstream file("data.csv"); if (!file.is_open()) { std::cerr << "Failed to open file." << std::endl; return 1; } std::string line; while (std::getline(file, line)) { std::stringstream ss(line); std::string cell; while (std::getline(ss, cell, ',')) { std::cout << cell << " | "; } std::cout << std::endl; } file.close(); return 0; }
Output
John | 25 | Developer |
Anna | 30 | Designer |
Mike | 22 | Tester |
Common Pitfalls
Common mistakes when reading CSV files in C++ include:
- Not checking if the file opened successfully before reading.
- Assuming all lines have the same number of columns.
- Not handling empty lines or trailing commas properly.
- Using
std::cininstead ofstd::ifstreamfor file input.
Always verify file open status and consider edge cases in your CSV data.
cpp
/* Wrong way: Not checking file open */ std::ifstream file("data.csv"); // No check if file is open /* Right way: Check file open */ std::ifstream file2("data.csv"); if (!file2.is_open()) { std::cerr << "Cannot open file." << std::endl; return 1; }
Quick Reference
Tips for reading CSV files in C++:
- Use
std::ifstreamto open files. - Read line by line with
std::getline. - Split lines using
std::stringstreamand comma delimiter. - Check file open status before reading.
- Handle empty or malformed lines gracefully.
Key Takeaways
Use std::ifstream and std::getline to read CSV files line by line in C++.
Split each line into cells using std::stringstream with comma as delimiter.
Always check if the file opened successfully before reading.
Handle empty lines and inconsistent columns carefully to avoid errors.
Close the file after finishing reading to free resources.