Open In App

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

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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::ifstream for 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++.

C++
//  C++ Program to illustrate how we can read data from a
//  CSV file into a 2D array
#include <fstream>
#include <iostream>
#include <sstream>
using namespace std;

// Maximum number of rows for the 2D array
const int MAX_ROWS = 100;
// Maximum number of columns for the 2D array
const int MAX_COLS = 100;

int main()
{
    // Open the CSV file
    ifstream file("data.csv");
    if (!file.is_open()) {
        cerr << "Error opening file!" << endl;
        return 1;
    }

    // Define a 2D array to store the CSV data
    string data[MAX_ROWS][MAX_COLS];
    string line;
    int row = 0;
    // Store the CSV data from the CSV file to the 2D array
    while (getline(file, line) && row < MAX_ROWS) {
        stringstream ss(line);
        string cell;
        int col = 0;
        while (getline(ss, cell, ',') && col < MAX_COLS) {
            data[row][col] = cell;
            col++;
        }
        row++;
    }
    // close the file after read opeartion is complete
    file.close();

    // Print the data stored in the 2D array
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < MAX_COLS && !data[i][j].empty();
             j++) {
            cout << data[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}


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)





Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads