In: Computer Science
How do I write a C++ program to call a frequency table from a csv file, using vector?
Data given is in a csv file. Below is part of the sample data.
Student ID | English | Math | Science |
100000100 | 80 | 90 | 90 |
100000110 | 70 | 60 | 70 |
100000120 | 80 | 100 | 90 |
100000130 | 60 | 60 | 60 |
100000140 | 90 | 80 | 80 |
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <string>
#include <algorithm>
#include <boost/algorithm/string.hpp>
/*
First, we will create a class to read frequency table from a csv file.
*/
class FileReader
{
std::string fileName;
std::string delimeter;
public:
FileReader(std::string filename, std::string delm = ",") :
fileName(filename), delimeter(delm)
{ }
// now we will create a Function to fetch frequency from a CSV File
std::vector<std::vector<std::string> > getData();
};
/*
* now we have to Parse through csv file line by line and returns the frequency data
* in vector of vector of strings.
*/
std::vector<std::vector<std::string> > FileReader::getData()
{
std::ifstream file(fileName);
std::vector<std::vector<std::string> > dataList;
std::string line = "";
// Iterate through each line and split the content using delimeter
while (getline(file, line))
{
std::vector<std::string> vec;
boost::algorithm::split(vec, line, boost::is_any_of(delimeter));
dataList.push_back(vec);
}
// Close the File
file.close();
return dataList;
}
int main()
{
// Creating an object of CSVWriter
FileReader reader("example.csv");
// Get the data from CSV File
std::vector<std::vector<std::string> > dataList = reader.getData();
// Print the content of row by row on screen
for(std::vector<std::string> vec : dataList)
{
for(std::string data : vec)
{
std::cout<<data << " , ";
}
std::cout<<std::endl;
}
return 0;
}