
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to read and parse CSV files in C++?
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
- Related Articles
- How to read CSV files in Golang?
- Python - Read all CSV files in a folder in Pandas?
- How to read CSV file in Python?
- How to parse JSON files in Golang?
- How to parse a CSV file using PHP
- How to Read and Writes Files in Ruby
- How to save a csv and read using fread in R?
- Using SAP ABAP, how can I read content of CSV files in a directory to an internal table?
- Write a Python code to read JSON data from a file and convert it to dataframe, CSV files
- How to read data from .csv file in Java?
- How to Handle Large CSV files with Pandas?
- How to read/parse JSON array using Java?
- How to read data from *.CSV file using JavaScript?
- How to read and write unicode (UTF-8) files in Python?
- Working with csv files in Java

Advertisements