LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Input/Output Programs · Question 6

Parse CSV sales data with stringstream in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Read CSV lines (skip the header), split each on commas, and print the revenue per region and the overall total, two decimals.

Solution
main.cpp
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string line;
    std::getline(std::cin, line);                // header
    double total = 0;
    std::cout << std::fixed << std::setprecision(2);
    while (std::getline(std::cin, line)) {
        std::istringstream row(line);
        std::string region, units_s, price_s;
        std::getline(row, region, ',');
        std::getline(row, units_s, ',');
        std::getline(row, price_s, ',');
        double revenue = std::stoi(units_s) * std::stod(price_s);
        total += revenue;
        std::cout << std::left << std::setw(6) << region << std::right << std::setw(10) << revenue << '\n';
    }
    std::cout << std::left << std::setw(6) << "Total" << std::right << std::setw(10) << total << '\n';
    return 0;
}

Output Verified by compiling and running

North    5940.00
South    4160.00
West     4488.75
Total   14588.75

getline with ',' extracts each field; std::stoi and std::stod convert the text to numbers. Reading the header first keeps it out of the calculation.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links