I am trying to create an algorithm where I can enter an input.csv
and output.csv
. I have remade the code and changed some areas to try to fix the issue.
One issue I am having right now is whenever I convert a string
to a double
using stod()
, it causes core dump issues when the program runs.
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <iomanip>
using namespace std;
// Function to split a string by a delimiter
vector<string> split(const string& s, char delimiter) {
vector<string> tokens;
string token;
istringstream tokenStream(s);
while (getline(tokenStream, token, delimiter)) {
tokens.push_back(token);
}
return tokens;
}
// Function to remove the lowest grade from a vector of grades
void removeLowest(vector<double>& grades)
{
auto it = min_element(grades.begin(), grades.end());
grades.erase(it);
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
cerr << "Usage: " << argv[0] << " input_file output_file" << endl;
return 1;
}
// Parse command line arguments
string inputFile(argv[1]);
string outputFile(argv[2]);
// Open input file
ifstream inFile(inputFile);
if (!inFile.is_open())
{
cerr << "Error opening input file: " << inputFile << endl;
return 1;
}
// Open output file
ofstream outFile(outputFile);
if (!outFile.is_open())
{
cerr << "Error opening output file: " << outputFile << endl;
return 1;
}
// Read header line
string header;
if (!getline(inFile, header))
{
cerr << "Error reading input file: " << inputFile << endl;
return 1;
}
// Parse maximum possible points for each lab
string maxPointsLine;
if (!getline(inFile, maxPointsLine))
{
cerr << "Error reading input file: " << inputFile << endl;
return 1;
}
vector<double> maxPoints;
for (const auto& token : split(maxPointsLine, ','))
{
maxPoints.push_back(stod(token));
}
// Write header line to output file
outFile << "name,points_earned,points_possible" << endl;
// Process each student line in input file
string line;
while (getline(inFile, line))
{
// Parse student name and grades
auto tokens = split(line, ',');
string name = tokens[0];
vector<double> grades;
for (size_t i = 1; i < tokens.size(); i++)
{
grades.push_back(stod(tokens[i]));
}
// Remove lowest grade
removeLowest(grades);
// Calculate earned points and possible points for this student
double pointsEarned = accumulate(grades.begin(), grades.end(), 0.0);
double pointsPossible = accumulate(maxPoints.begin(), maxPoints.end(), 0.0);
// Write data to output file
outFile << name << ",";
outFile << fixed << setprecision(2) << pointsEarned << ",";
outFile << fixed << setprecision(2) << pointsPossible << endl;
// Close input and output files
inFile.close();
outFile.close();
return 0;
}
}