C++ basic custom cout printing to consle

728 views Asked by At
template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{
    os << s << " = (\n";

    os << charInput1;
    std::copy(first, last, std::ostream_iterator<int>(std::cout, "\n"));
    os << charInput2;

    os << "\n)";
}

I'm trying to do a custom cout print. This member function belong to a class CustomPrinter, and the charInput1 and charInput2 are its private char members, which is defined when I construct a custom printer. The first and last are supposed to be iterators, and s is a string.

So for example, given charInput1 is a + sign, and charInput2 is a period ., I would expect the final output to be the following, given a std::vector<int> = {1, 1, 1}:

(
+1.
+1.
+1.
)

But I'm getting

(
+1
1
1
.
)

So my question is, what else is needed in order to print the given char in between each vector element? Is it possible to only use the std::ostream_iterator<int>(std::cout, /* char here? */)? Because it seems that this method can only insert strings in between, I need to insert before as well. If not, what can be a better approach? Thanks in advance!

Edit: In my main I have

CustomPrinter cp(std::cout, '+', '.');
std::vector<int> v = {1, 1, 1};
cp.print("result", v.begin(), v.end()); // function call..
1

There are 1 answers

3
Barmar On BEST ANSWER

Just use an ordinary loop:

template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{
    os << s << " = (\n";
    for (auto el = first; el != last; el++) {
        os << charInput1 << *el << charInput2 << "\n";
    }    
    os << ")";
}

Actually, you can do it using std::ostream_iterator, by concatenating your surrounding characters.

template<typename T, typename F, typename L>
void print(const T& s, F first, L last)
{

    std::string sep = charInput1 + std::string("\n") + charInput2;
    os << s << " = (\n";
    if (first != last) { // Don't print first prefix and last suffix if the sequence is empty
        os << charInput1;
        std::copy(first, last, std::ostream_iterator<int>(std::cout, sep.c_str()));
        os << charInput2;
    }
    os << "\n)";
}