How to read data from CSV file in C++
Today we are going to perform reading operations on a CSV file using C++. Let’s learn how to read data from CSV file in C++.
Reading a CSV file in C++
CSV file is a comma-separated file which allows the data to store in tabular form. We can store data in CSV file and read it. The data is used for performing various functions.
Reading a file first we need to declare an object with function ifstream open the file in open function.
ifstream fin;
Then we have to open an already created file using an object.
fin.open("report.csv");Then using a while loop we are going to read the file and display it. We have also created a string to read, store and display data using a string.
string line;
while(!fin.eof()){
fin>>line;
cout<<line<<" ";
}In this while loop eof() is used to run the loop till the end.
C++ code to read a CSV file
#include <iostream>
#include<fstream>
using namespace std;
void read()
{
ifstream fin;
string line;
// Open an existing file
fin.open("report.csv");
while(!fin.eof()){
fin>>line;
cout<<line<<" ";
}
}
int main()
{
read();
return 0;
}We are opening a preexisting file that contains data.
Data: 1 Ram 55
Output:
1,ram,55
You may also read:
What if I want to search, “ram” and get output “Yes, 1” (Where 1 is index or serial no of “ram” in the preexisting file, “YES” as data exists)