Draw A Rectangle With Asterisks

前端 未结 4 1441
眼角桃花
眼角桃花 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: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;
        }
    }
    

提交回复
热议问题