John Escobia John Escobia - 3 months ago 15
C++ Question

How to display two functions next to each other in C++?

The output of my code shows

function1()
above
function2()
. Is there a way to code so that the output would show
function1()
next to (as in side by side)
function2()
?

Below is a snippet of my code:

#include <iostream>
using namespace std;

void function1()
{
int i;
int array[5] = {5, 5, 5, 5, 5};

cout << " -1-2-3-4-5-" << endl;
cout << " |";
for (i = 0; i < 5; ++i)
cout << array[i] << "|";
cout << endl;
}

void function2()
{
int i;
char array[5] = {'A', 'A', 'A', 'A', 'A'};

cout << " -1-2-3-4-5-" << endl;
cout << " |";
for (i = 0; i < 5; ++i)
cout << array[i] << "|";
cout << endl;
}

int main()
{

function1();
function2();

return 0;
}

Answer

This is possible but not completely untricky.

The trick I used here is to pass the output stream to the function rather than have the function print to std::cout directly. This allows me to pass a std::stringstream to the function which prints to that instead. The std::stringstream captures the output for later where I have a function to print both outputs one line at a time, next to each other:

#include <sstream>
#include <iostream>

// output to a generic output stream
// rather than hard-coding std::cout
void function1(std::ostream& os)
{
    int i;
    int array[5] = { 5, 5, 5, 5, 5 };

    os << "   -1-2-3-4-5-" << '\n';
    os << "   |";
    for(i = 0; i < 5; ++i)
        os << array[i] << "|";
    os << '\n';
}

void function2(std::ostream& os)
{
    int i;
    char array[5] = { 'A', 'A', 'A', 'A', 'A' };

    os << "   -1-2-3-4-5-" << '\n';
    os << "   |";
    for(i = 0; i < 5; ++i)
        os << array[i] << "|";
    os << '\n';
}

// read each input stream line by line, printing them side by side
void side_by_side(std::istream& is1, std::istream& is2, std::size_t width)
{
    std::string line1;
    std::string line2;

    while(std::getline(is1, line1))
    {
        std::string pad;

        // ensure we add enough padding to make the distance
        // the same regardless of line length
        if(line1.size() < width)
            pad = std::string(width - line1.size(), ' ');

        // get same line from second stream
        std::getline(is2, line2);

        // print them size by the side the correct distance (pad)
        std::cout << line1 << pad << line2 << '\n';
    }

    // in case second stream has more line than the first
    while(std::getline(is2, line2))
    {
        auto pad = std::string(width, ' ');
        std::cout << pad << line2;
    }
}

int main()
{
    // some stream objects to store the outputs
    std::stringstream ss1;
    std::stringstream ss2;

    // capture output in stream objects
    function1(ss1);
    function2(ss2);

    // print captured output side by side
    side_by_side(ss1, ss2, 30);
}

Output:

   -1-2-3-4-5-                   -1-2-3-4-5-
   |5|5|5|5|5|                   |A|A|A|A|A|