For the first problem, a suggestion is to encapsulate the labels´print in a function:
1) Store your column names at a constant std::array
or std::vector
.
#include<vector>
const std::vector<std::string> col_labels = {"col_label1, col_label2, col_label3"};
So you may get something like:
void printHeaders(std::ofstream& outputStream){
const std::vector<std::string> col_labels = {"col_label1",
"col_label2",
"col_label3"};
for(auto& label: col_labels){
outputStream << label << "\t";
}
}
2) For the second, if you have different print patterns, for instance, you can use std::function
to pass function as parameters to other functions and have more control over the patterns. You can declare the functions will be used as parameters or use a lambda expression.
NOTE: You're going to need C++11 support in your compiler. In g++
use the std=c++11
option.
For instance, suppose you have two different patterns:
a) Enclose the field value in *
b) Enclose the field value in (
)
c) Enclose the field value in --
--
#include<fstream>
#include<functional>
#include<string>
std::string formatAsterix(const std::string& str){
//bad design concat std::strings... just to show the idea
return std::string("*") + str + std::string("*");
}
std::string formatParenthesis(const std::string& str){
return std::string("(") + str + std::string(")");
}
void printFormatted(std::ofstream& outputStream, /*Your output stream*/
const std::string str, /*your string*/
std::function<std::string(const std::string&)> formatter ) /*your formatter function*/
{
outputStream << formatter(str) << std::endl;
}
int main(){
std::ofstream outputStream;
outputStream.open("c:\\tmp\\out.txt");
printFormatted(outputStream, "FIELD_VALUE", formatAsterix);
printFormatted(outputStream, "FIELD_VALUE", formatParenthesis);
// This last one uses a lamba expression
printFormatted(outputStream, "FIELD_VALUE",
[&](const std::string str)
{
return std::string("-- ") + str + std::string(" --");
});
outputStream.close();
}
Executing the program, you´ll get:
*FIELD_VALUE*
(FIELD_VALUE)
-- FIELD_VALUE --
I hope these examples could show you a test of functional programming in C++.