Draw A Rectangle With Asterisks

前端 未结 4 1439
眼角桃花
眼角桃花 2021-01-29 13:23

I am trying to write a C++ Program to display a rectangle drawn in asterisks. I have the program running properly except for the fact that only one side of the heights of my rec

相关标签:
4条回答
  • 2021-01-29 13:40

    Specify a width and height at the start then you only need 3 loops. The first will print the top line of the rectangle. The second will print both sides of the rectangle (minus the very top and very bottom of the sides). The third will print the bottom line of the rectangle.

    Like so

    // Width and height must both be at least 2
    unsigned int width = 7;  // Example value
    unsigned int height = 5; // Example value
    // Print top row
    for(unsigned int i = 0; i < width; i++);
    {
        std::cout << "*";
    }
    std::cout << std::endl;
    // Print sides
    for(unsigned int i = 0; i < height - 2; i++)
    {
        std::cout << std::setw(width - 1) << std::left << "*";
        std::cout << "*" << std::endl;
    }
    // Print bottom row
    for(unsigned int i = 0; i < width; i++)
    {
        std::cout << "*";
    }
    std::endl;
    

    You will need to include both iostream and iomanip for this to work (setw is part of iomanip).

    The top and bottom rows could also be done using the method to fill spaces with a given character, but I cannot recall that method right now.

    0 讨论(0)
  • 2021-01-29 13:43

    Well, you don't see the second vertical line, because you don't draw it in your line loop.

    void DrawRect(int w, int h, char c)
    {
        cout << string(w, c) << '\n';
        for (int y = 1; y < h - 1; ++y)
            cout << c << string(w - 2, ' ') << c << '\n';
        cout << string(w, c) << '\n';
    }
    
    0 讨论(0)
  • 2021-01-29 13:47

    This can be done much easier and clearer.
    The logic here is to draw from line to line, so you only need one loop
    (I chose to use the auto specifier in this example because I think it looks neater and used often in modern c++, if your compiler doesn't support c++11, use char, int etc.):

    int main()
    {
        using namespace std;
    
        auto star      = '*';
        auto space     = ' ';
        auto width     = 20;
        auto height    = 5;
        auto space_cnt = width-2;
    
        for (int i{0}; i != height+1; ++i) {
            // if 'i' is the first line or the last line, print stars all the way.
            if (i == 0 || i == height)
                cout << string(width, star) << endl;
            else // print [star, space, star]
                cout << star << string(space_cnt, space) << star << endl;
        }
    }
    
    0 讨论(0)
  • 2021-01-29 13:56

    Try to prompt the user for the number of rows and columns. Then, using nested loops, display a rectangle of stars based on the user input.

    0 讨论(0)
提交回复
热议问题