繁体   English   中英

如何在C ++中显示彼此相邻的两个函数?

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

我的代码输出显示function1()上面的function2() 有没有办法进行编码,以便输出显示function1()旁边(如并排) function2()

以下是我的代码片段:

#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;
}

这是可能的,但并非完全不合适。

我在这里使用的技巧是将输出流传递给函数,而不是直接将函数打印到std::cout 这允许我将std :: stringstream传递给打印到该函数的函数。 std :: stringstream捕获输出以便稍后我有一个函数一次打印两行输出,彼此相邻:

#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);
}

输出:

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

不,那里没有。

首先调用function1()然后调用function2() ,这样它们就会一个接一个地执行。

然而,你可以做的是,让这些函数只返回数据作为数组或向量,然后在收集到两个结果后处理输出。

另一种选择是使函数始终只处理一次迭代(您可能希望使用static int i或类似的),然后在函数调用之外循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM