使用for循环绘制边框

时间:2016-05-23 22:18:25

标签: c++ c++11 for-loop

我正在尝试使用for循环创建一个简单的边框。我得不到合适的结果。具体来说,我的右边框没有显示。请帮忙。

const int width = 20;
const int height = 20;

void Drow() 
{
    system("cls");                      // clear the screan
    for (int i = 0; i < width; ++i) 
    {
        cout << "*";                    // upper border
    }       

    for (int i = 0; i < height-2; i++) 
    {
        for (int j = 0; j < width; j++) 
        {
            if (j == 0 || j == width - 1)
            {
                cout << "*";            // left and right borders
            }
        }
        cout << endl;
    }

    for (int i = 0; i < width; i++)     // lower border
        cout << "*";
}

2 个答案:

答案 0 :(得分:3)

在第二个循环中,绘制边框但是忘记绘制矩形的内部。

将其添加到if

else {
    cout << " ";
}

正如πάνταῥεῖ指出的那样,你也忘了在第一次和最后一次循环之后使用endl

Live Demo

答案 1 :(得分:1)

除非我感到受到严重的自虐,否则我的工作会有所不同。

我的立即反应是在这个通用顺序上编写更多代码:

std::string h_border = std::string(width, '*' ) + "\n";
std::string v_border = "*" + std::string(width - 2,  ' ') +"*\n";

std::cout << h_border;
for (int i = 0; i < height - 2; i++)
    std::cout << v_border;
std::cout << h_border;
相关问题