![]() |
VOOZH | about |
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} }
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.
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)