cplusplus
cplusplus

 

Introduction

In this tutorial, we will learn how to parse a CSV (Comma Separated Values) file and display its contents using C++. A CSV file stores tabular data in plain text form, where each row is a line, and columns are separated by commas. It is widely used for data exchange and storage due to its simplicity.

Objective

The goal of this program is to read data from a CSV file, parse it, and display the contents in a user-friendly format. We’ll focus on using standard C++ libraries like fstream and sstream to handle file I/O and string manipulation. By the end of this tutorial, you’ll have a basic understanding of file reading, data extraction, and displaying results in C++.

Code

#include 
#include 
#include 
#include 

using namespace std;

// Function to parse and display CSV content
void parseCSV(const string& filename) {
    ifstream file(filename);  // Open the file
    string line;
    
    if (!file.is_open()) {
        cout << "Error: Could not open the file!" << endl;
        return;
    }
    
    // Read and process each line of the CSV file
    while (getline(file, line)) {
        stringstream ss(line);  // Use stringstream to parse each line
        string cell;
        
        // Parse each cell in the line
        while (getline(ss, cell, ',')) {
            cout << cell << "\t";  // Display each cell separated by a tab
        }
        cout << endl;  // Print a new line after each row
    }

    file.close();  // Close the file
}

int main() {
    string filename = "data.csv";  // Specify the CSV file name
    parseCSV(filename);  // Call the function to parse and display CSV content
    return 0;
}

Explanation of Program Structure

The program is organized as follows:

  • Includes: We include the necessary header files:
    • #include <iostream>: For input-output operations.
    • #include <fstream>: For reading files.
    • #include <sstream>: For string stream manipulation (to split the line into columns).
    • #include <string>: For string handling.
  • parseCSV function: This function handles the parsing of the CSV file:
    • It opens the file using an ifstream object.
    • For each line in the file, it uses a stringstream to break the line into individual cells (separated by commas).
    • Each cell is printed with a tab space between them.
    • If the file cannot be opened, it prints an error message.
  • main function: This is where the execution begins. It specifies the CSV file (in this case, “data.csv”) and calls the parseCSV function to parse and display its contents.

How to Run the Program

To run this program, follow these steps:

    1. Ensure you have a CSV file named data.csv in the same directory as your program, or modify the file path in the code.
    2. Open a terminal and navigate to the directory where the program is located.
    3. Compile the program using a C++ compiler, such as g++:
g++ -o parse_csv parse_csv.cpp
    1. Run the compiled program:
./parse_csv
  1. The program will display the contents of the CSV file, where each row will be printed with each value separated by tabs.
© 2024 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)