CSV file management using C++
Files in the CSV (Comma-Separated Values) format are widely used to store tabular data. Each line in the file corresponds to a row in the table, and commas are used to separate the values in each row. C++ offers a number of libraries and methods to work with CSV files. It is a quick overview of using C++ to manage CSV files.
1. Create Operation:
The create process is comparable to creating a text file in that it involves obtaining user input, writing it to a CSV file, and inserting the appropriate delimiters (', ') between columns and '\n' at the end of each row.
Syntax:
It has the following syntax:
#include <iostream>
#include <fstream>
using namespace std;
void create()
{
// file pointer
fstream fout;
// opens an existing csv file or creates a new file.
fout.open("reportcard.csv", ios::out | ios::app);
cout << "Enter the details of 5 students:"
<< " roll name math phy chem bio english history";
cout << endl;
int i, roll, phy, chem, math, bio, english, history;
string name;
// Read the input
for (i = 0; i < 5; i++) {
cout << "Enter details for student " << i + 1 << ":" << endl;
cin >> roll >> name >> math >> phy >> chem >> bio >> english >> history;
// Insert the data to file
cout << roll << ", " << name << ", " << math << ", " << phy << ", " << chem << ", " << bio << ", " << english << ", " << history << "\n";
}
fout.close();
}
2. Reading the Particular Record:
The following method is used when reading a CSV file:
- Get the contents of a row and store it in a string variable by using getline(), the file pointer, and the delimiter "\n".
- Create words out of the row using stringstream.
- Use getline(), the stringstream pointer, and ',' as the delimiter to read every word in the row. After that, store each word in a string variable and push it to a string vector.
- Retrieve the necessary column data by using the row[index]. Since row[0] always contains a student's roll number in this case, compare row[0] to the roll number that the user has entered. If the two match, show the student's details and end the loop.
C++ CODE:
Let us take an example to illustrate the CSV File Management using C++.
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
using namespace std;
// Function to create a CSV file and input data
void createCSV() {
// File pointer
ofstream fout;
// Opens a new CSV file
fout.open("students.csv", ios::out);
cout << "Enter the details of 5 students: roll, name, math, phy, chem, bio" << endl;
int roll, phy, chem, math, bio;
string name;
// Read input for 5 students
for (int i = 0; i < 5; i++) {
cout << "Enter details for student " << i + 1 << ":" << endl;
cin >> roll >> name >> math >> phy >> chem >> bio;
// Insert data to file
fout << roll << "," << name << "," << math << "," << phy << "," << chem << "," << bio << "\n";
}
cout << "CSV file created successfully." << endl;\
// Close the file
fout.close();
}
// Function to read and display data from a CSV file
void readCSV() {
// File pointer
ifstream fin;
// Opens an existing CSV file
fin.open("students.csv", ios::in);
if (!fin.is_open()) {
cout << "Error opening file. Make sure to create the file first." << endl;
return;
}
cout << "Student Details from CSV File:" << endl;
string line, word;
vector<string> row;
// Read data from file and display
while (getline(fin, line)) {
row.clear();
stringstream s(line);
while (getline(s, word, ',')) {
row.push_back(word);
}
// Assuming the CSV format is roll, name, math, phy, chem, bio
cout << "Roll: " << row[0] << ", Name: " << row[1] << ", Math: " << row[2]
<< ", Physics: " << row[3] << ", Chemistry: " << row[4] << ", Biology: " << row[5] << endl;
}
// Close the file
fin.close();
}
int main() {
createCSV(); // Create a CSV file and input data
readCSV(); // Read and display data from the CSV file
return 0;
}
Output:
// Input during createCSV():
1 HARSHA 90 85 75 95
2 VARDHAN 80 92 88 78
3 POOJITHA 95 88 75 90
4 RAM 85 90 92 80
5 SHYAM 88 85 90 78
// Output during readCSV():
Student Details from CSV File:
Roll: 1, Name: HARSHA, Math: 90, Physics: 85, Chemistry: 75, Biology: 95
Roll: 2, Name: VARDHAN, Math: 80, Physics: 92, Chemistry: 88, Biology: 78
Roll: 3, Name: POOJITHA, Math: 95, Physics: 88, Chemistry: 75, Biology: 90
Roll: 4, Name: RAM, Math: 85, Physics: 90, Chemistry: 92, Biology: 80
Roll: 5, Name: SHYAM, Math: 88, Physics: 85, Chemistry: 90, Biology: 78
Example 2:
Let us take another example to illustrate the CSV File Management using C++.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <iterator>
using namespace std;
// Function to read and display data from a CSV file without knowing the column names
void readCSV() {
ifstream fin("data.csv"); // Replace "data.csv" with your CSV file name
if (!fin.is_open()) {
cerr << "Error opening file for reading. Make sure to create the file first." << endl;
return;
}
cout << "CSV File Contents:" << endl;
vector<vector<string>> data; // Vector to store CSV data
string line;
while (getline(fin, line)) {
stringstream ss(line);
vector<string> row;
while (getline(ss, line, ',')) {
row.push_back(line);
}
data.push_back(row);
}
fin.close();
// Display the CSV data
for (const auto& row : data) {
copy(row.begin(), row.end(), ostream_iterator<string>(cout, "\t"));
cout << endl;
}
}
int main() {
readCSV(); // Read and display data from the CSV file
return 0;
}
Output:
Error opening file for reading. Make sure to create the file first.
Example 3:
Let us take another example to illustrate the CSV File Management using C++.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
struct Student {
int roll;
string name;
int math;
int phy;
int chem;
int bio;
};
// Function to create a CSV file and input data
void createCSV() {
ofstream fout("students.csv", ios::out);
if (!fout.is_open()) {
cerr << "Error opening file for writing." << endl;
return;
}
cout << "Enter the details of 5 students: roll, name, math, phy, chem, bio" << endl;
vector<Student> students;
for (int i = 0; i < 5; i++) {
cout << "Enter details for student " << i + 1 << ":" << endl;
Student student;
cin >> student.roll >> student.name >> student.math >> student.phy >> student.chem >> student.bio;
students.push_back(student);
// Write data to file
fout << student.roll << ',' << student.name << ',' << student.math << ',' << student.phy
<< ',' << student.chem << ',' << student.bio << '\n';
}
cout << "CSV file created successfully." << endl;
fout.close();
}
// Function to read and display data from a CSV file
void readCSV() {
ifstream fin("students.csv", ios::in);
if (!fin.is_open()) {
cerr << "Error opening file for reading. Make sure to create the file first." << endl;
return;
}
cout << "Student Details from CSV File:" << endl;
vector<Student> students;
string line;
while (getline(fin, line)) {
stringstream ss(line);
Student student;
ss >> student.roll;
ss.ignore(); // Ignore the comma
getline(ss, student.name, ',');
ss >> student.math;
ss.ignore(); // Ignore the comma
ss >> student.phy;
ss.ignore(); // Ignore the comma
ss >> student.chem;
ss.ignore(); // Ignore the comma
ss >> student.bio;
students.push_back(student);
cout << "Roll: " << student.roll << ", Name: " << student.name << ", Math: " << student.math
<< ", Physics: " << student.phy << ", Chemistry: " << student.chem << ", Biology: " << student.bio << endl;
}
fin.close();
}
int main() {
createCSV(); // Create a CSV file and input data
readCSV(); // Read and display data from the CSV file
return 0;
}
Output:
/tmp/GIvUC4foZO.o
Enter the details of 5 students: roll, name, math, phy, chem, bio
Enter details for student 1:
hello
Enter details for student 2:
Enter details for student 3:
Enter details for student 4:
Enter details for student 5:
CSV file created successfully.
Student Details from CSV File:
Roll: 0, Name: , Math: 0, Physics: 0, Chemistry: 0, Biology: 0
Roll: 0, Name: , Math: 0, Physics: 0, Chemistry: 0, Biology: 0
Roll: 0, Name: , Math: 0, Physics: 0, Chemistry: 0, Biology: 0
Roll: 0, Name: , Math: 0, Physics: 0, Chemistry: 0, Biology: 0
Roll: 0, Name: , Math: 0, Physics: 0, Chemistry: 0, Biology: 0
Conclusion:
C++'s file handling and string manipulation libraries can be used to efficiently read from and write to Comma-Separated Values (CSV) files. It is known as CSV file management. With the help of features like file streams, string streams, and suitable data structures, the examples given show how to create, input, and read from CSV files. Developers are able to create CSV handling mechanisms that are customized to meet particular needs due to C++'s flexibility, which makes data manipulation and organization easier. Integrity and dependability in managing a variety of datasets are ensured by taking error handling and data validation into account when putting CSV file management into practice. Depending on the complexity of the CSV data and the needs of the particular project, additional libraries like Boost Tokenizer or external CSV parsing libraries may be investigated for more advanced solutions. Overall, C++'s extensive toolkit for string processing and file input/output makes it easier to manage CSV files and gives developers more flexibility when working with tabular data.