C++ Program to Read a CSV File and Calculate the Total
CSV files are everywhere. This program reads a small sales file, skips the header, ignores bad lines and shows the total and the average.
Program
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
struct Sale {
std::string item;
int quantity;
double price;
double amount() const { return quantity * price; }
};
std::vector<std::string> split(const std::string& line, char sep) {
std::vector<std::string> parts;
std::istringstream in(line);
std::string part;
while (std::getline(in, part, sep)) parts.push_back(part);
return parts;
}
int main() {
std::ofstream("sales.csv") << "item,quantity,price\nPen,10,5.50\nBook,2,250\nBag,1,899.99\nBroken line\nNotebook,abc,40\n";
std::ifstream in("sales.csv");
std::string line;
std::getline(in, line); // skip the header
std::vector<Sale> sales;
while (std::getline(in, line)) {
auto p = split(line, ',');
if (p.size() != 3) {
std::cout << "Skipped (wrong columns): " << line << '\n';
continue;
}
try {
sales.push_back({p[0], std::stoi(p[1]), std::stod(p[2])});
} catch (const std::exception&) {
std::cout << "Skipped (bad number): " << line << '\n';
}
}
double total = 0;
std::cout << std::fixed << std::setprecision(2);
for (const auto& s : sales) {
std::cout << std::left << std::setw(10) << s.item << std::right << std::setw(8) << s.amount() << '\n';
total += s.amount();
}
std::cout << "Total: " << total << '\n';
std::cout << "Average per row: " << total / sales.size() << '\n';
}
Output
Skipped (wrong columns): Broken line
Skipped (bad number): Notebook,abc,40
Pen 55.00
Book 500.00
Bag 899.99
Total: 1454.99
Average per row: 485.00
Notes
std::getline(in, part, ',')splits a text by a character.std::stoiandstd::stodthrow an exception for a bad number, so we catch it and skip the line.- If a value can contain a comma inside quotes, use a CSV library.
Related: C++ File Handling and C++ Exceptions.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |