LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Abstract Class Programs · Question 3

Exporting student marks to CSV, TSV and Markdown in C++ Solution, output & explanation

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

Write a Formatter interface with header(), row() and footer(), implement CSV, TSV and Markdown table formatters, and write a single export function that works with any of them.

Solution
main.cpp
#include <iostream>
#include <string>
#include <vector>

struct Formatter {
    virtual std::string header() const = 0;
    virtual std::string row(const std::string& name, int marks) const = 0;
    virtual std::string footer() const { return ""; }      // optional hook
    virtual ~Formatter() = default;
};

struct Csv : Formatter {
    std::string header() const override { return "name,marks\n"; }
    std::string row(const std::string& n, int m) const override { return n + "," + std::to_string(m) + "\n"; }
};
struct Tsv : Formatter {
    std::string header() const override { return "name\tmarks\n"; }
    std::string row(const std::string& n, int m) const override { return n + "\t" + std::to_string(m) + "\n"; }
};
struct Markdown : Formatter {
    std::string header() const override { return "| name | marks |\n|---|---|\n"; }
    std::string row(const std::string& n, int m) const override { return "| " + n + " | " + std::to_string(m) + " |\n"; }
    std::string footer() const override { return "_end of table_\n"; }
};

struct Student { std::string name; int marks; };

std::string export_all(const std::vector<Student>& s, const Formatter& f) {
    std::string out = f.header();
    for (const auto& x : s) out += f.row(x.name, x.marks);
    return out + f.footer();
}

int main() {
    std::vector<Student> s{{"Asha", 91}, {"Ravi", 78}};
    std::cout << export_all(s, Csv{}) << export_all(s, Tsv{}) << export_all(s, Markdown{});
    return 0;
}

Output Verified by compiling and running

name,marks
Asha,91
Ravi,78
name	marks
Asha	91
Ravi	78
| name | marks |
|---|---|
| Asha | 91 |
| Ravi | 78 |
_end of table_

header() and row() are required; footer() is an optional hook with a default, overridden only by Markdown.

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