如何在C++中打印垂直直方图

Spi*_*ico 3 c++ loops

#include <iostream>
using namespace std;
int main()
{
    int a, b, c, i;
    cin >> a >> b >>  c;

    for ( i = 0;  i < a; i++)
        cout << "*" << endl;

    for ( i = 0; i < b; i++)
        cout << "*" << endl;

    for ( i = 0; i < c; i++)
        cout << "*" << endl;
}
Run Code Online (Sandbox Code Playgroud)

我知道输出与:

for ( i = 0; i < a + b + c; i++ ){
cout << "*" << endl;
}
Run Code Online (Sandbox Code Playgroud)

因此对于2 3 1我得到:

*

*

*

*

*

*

我想要的是:

     *

*    * 

*    *    *   //Horizontal distance between 2 shapes don't matter.
Run Code Online (Sandbox Code Playgroud)

我不知道如何将光标放在正确的位置,因为打印必须从上到下完成.

编辑:我不清楚打印的顺序.我希望以下示例有所帮助,如果可能的话,每列的打印必须使用单独的功能.

第一循环:

*

*
Run Code Online (Sandbox Code Playgroud)

第二循环:

    *

*   *

*   *
Run Code Online (Sandbox Code Playgroud)

最后一个循环

    *

*   *

*   *   *
Run Code Online (Sandbox Code Playgroud)

打印必须完全按照该顺序进行.打印第一列,然后打印第二列,然后继续打印.

Som*_*ude 5

您需要重新考虑一下您的打印.首先,您需要找出最高的列,因为这是您将拥有的行数.

我会做这样的事情:

int high = std::max(std::max(a, b), c);

for (int i = high; i > 0; i--)
{
    if (i <= a)
        std::cout << " * ";
    else
        std::cout << "   ";

    if (i <= b)
        std::cout << " * ";
    else
        std::cout << "   ";

    if (i <= c)
        std::cout << " * ";
    else
        std::cout << "   ";

    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要任意数量的列,你可能想把它们放在一个std::vector,并有一个内部循环.


对于任意数量的列,您可以使用以下内容:

// Get the input
std::cout << "Please enter numbers, all on one line, and end with ENTER: ";
std::string input;
std::getline(std::cin, input);

// Parse the input into integers
std::istringstream istr(input);
std::vector<int> values(std::istream_iterator<int>(istr),
                        std::istream_iterator<int>());

// Get the max value
int max_value = *std::max_element(values.begin(), values.end());

// Print the columns
for (int current = max_value; current > 0; current--)
{
    for (const int& value : values)
    {
        if (current <= value)
            std::cout << " * ";
        else
            std::cout << "   ";
    }

    std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)