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.
- It opens the file using an
- 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:
-
- Ensure you have a CSV file named
data.csv
in the same directory as your program, or modify the file path in the code. - Open a terminal and navigate to the directory where the program is located.
- Compile the program using a C++ compiler, such as
g++
:
- Ensure you have a CSV file named
g++ -o parse_csv parse_csv.cpp
-
- Run the compiled program:
./parse_csv
- The program will display the contents of the CSV file, where each row will be printed with each value separated by tabs.