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.
More Abstract Classes and Interfaces practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!