LearnFrenzy
Sign in Take a free test

Modern C++ Features (C++11 to C++23) · Modern C++ Programs · Question 3

CSV bill with string_view and std::format in C++ Solution, output & explanation

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

Parse "item,qty,price" CSV lines with string_view and from_chars into structs using designated initialisers, then print an aligned bill with std::format.

Solution
main.cpp
#include <charconv>
#include <format>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

struct Line { std::string item; int qty; double price; };

template <typename T>
T to_number(std::string_view s) { T v{}; std::from_chars(s.data(), s.data() + s.size(), v); return v; }

Line parse(std::string_view row) {
    auto c1 = row.find(','), c2 = row.find(',', c1 + 1);
    return {.item = std::string(row.substr(0, c1)),
            .qty = to_number<int>(row.substr(c1 + 1, c2 - c1 - 1)),
            .price = to_number<double>(row.substr(c2 + 1))};
}

int main() {
    std::vector<std::string_view> csv{"Notebook,4,60", "Pen,10,12.5", "Backpack,1,899"};
    double total = 0;
    std::cout << std::format("{:<10}{:>5}{:>9}{:>10}\n", "Item", "Qty", "Price", "Amount");
    for (auto row : csv) {
        auto [item, qty, price] = parse(row);
        total += qty * price;
        std::cout << std::format("{:<10}{:>5}{:>9.2f}{:>10.2f}\n", item, qty, price, qty * price);
    }
    std::cout << std::format("{:<10}{:>24.2f}\n", "TOTAL", total);
    return 0;
}

Output Verified by compiling and running

Item        Qty    Price    Amount
Notebook      4    60.00    240.00
Pen          10    12.50    125.00
Backpack      1   899.00    899.00
TOTAL                      1264.00

from_chars (C++17) parses numbers straight from views without exceptions or locales; designated initialisers make the struct creation self-documenting.

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