Get particular column from a CSV file in C++

We can access the CSV file in C++ using the reading function. So, today we are going to perform this.

CSV file:

CSV file is a comma-separated file used to collect the data in tabular format. The file contains the CSV file extension. We can store the data in a file in a tabular format with a comma. We can collect the data using a different medium and collect it in a CSV file. CSV file is used as a universal format for data collection.

We can add the data in a file using file handling using a function with an object.

ofstream object;

We can read these files using a function with an object.

ifstream object;

We can store this data in a CSV file using these function and read a particular record also.

C++ program to get particular column from a CSV file

#include <iostream>
#include<fstream>
#include<stdlib.h>
using namespace std;

void read_record()
{
    ifstream fin;
    string name;
    int rollnum,roll;
    roll=1;
    fin.open("reportcard.csv");
     while(!fin.eof())
       {
           fin>>rollnum;
           if(roll==rollnum)
               {
                  fin>>name;
                  cout<<name;
                  exit(0);
               }
        }

}

int main()
{
    read_record();
    return 0;
}

My CSV file contains roll number, name and marks i.e. 1, ram, 55.

Output:

ram

In this output first, we are going to compare the roll number of a student and then we are going to display a particular column in of CSV file.

Also read: How to read data from CSV file in C++

Leave a Reply

Your email address will not be published.