VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-read-data-from-csv-file-to-a-2d-array-in-cpp/

⇱ How to Read Data from a CSV File to a 2D Array in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Read Data from a CSV File to a 2D Array in C++?

Last Updated : 23 Jul, 2025

A comma-separated value file also known as a CSV file is a file format generally used to store tabular data in plain text format separated by commas. In this article, we will learn how we can read data from a CSV file and store it in a 2D array in C++.

Example:

Input: 
CSV File = “data.csv”
//contains: 1, Student1, C++ 2, Student2, Java 3, Student3, Python

Output: 
2D array elements: { {1, Student1, C++},
 {2, Student2, Java},
 {3, Student3, Python} }

Read CSV Data into a 2D Array in C++

To read data from a CSV file into a 2D array in C++, we can use the file streams from the standard library,std::ifstreamfor reading from files to read the file line by line, and for each line, we use a std::stringstream to split the line into individual values using the comma as a delimiter.

Note: All this data will be stored as a single data types as array cannot contain different data types. One way is to store all the data in the string and then convert it later accordingly.

C++ Program to Read data from a CSV file into a 2D Array

The following program illustrates how we can read data from a CSV file into a 2D array in C++.


Output

1 Student1 C++ 2 Student2 Java 3 Student3 Python

Time Complexity: O(R * C), here R is the number of rows and C is the number of columns.
Auxiliary Space: O(R * C)



Comment