C ++如何使用用户输入创建空心框/矩形?

时间:2016-02-25 20:01:19

标签: c++ for-loop box

我目前正在开展一个项目,提示用户输入他们想要用于盒子的高度,宽度和角色。我必须使用for循环创建一个坚固的空心框。我已经创造了一个没有问题的坚固的,但是当谈到空心的那个时,我遇到了一些问题。任何帮助表示赞赏。

int main()

{
    int height;
    int width;
    int i, j;
    char ch;

    cout << "Please enter your height: ";
    cin >> height;

    cout << "Please enter your width: ";
    cin >> width;

    cout << "Please enter your character: ";
    cin >> ch;

    for (i = 1; i <= height; i++)
    {
        for (j = 1; j <= width; j++)
            cout << ch;
        cout << endl;
    }

    cout << "Press any key to continue to the next shape." << endl;
    _getch();

    for (i = 1; i <= height; i++)
    {
        for (j = 1; j <= width; j++)
        {
            if (i == 1 || i == width -1 || j == 1 || j == height )
                cout << ch; 
            else cout << " ";
        }
        cout << endl;
    }

    system("pause");
    return 0;

}

2 个答案:

答案 0 :(得分:1)

您可以在嵌套for循环中编写它:

if( (i==1 || i==height) || (j==1 || j==width))
    cout << ch;
else
    cout << " ";

答案 1 :(得分:0)

这是写一个空心框的代码。 w是宽度,h是高度,c是要使用的字符。

int w, h;
char c;

int i, j;

/* write the first line */
for (i = 0; i < w; ++i)
    putchar(c);
putchar('\n');

/* write the inner lines */
for (j = 0; j < h - 2; ++j) {
    putchar(c);
    for (i = 0; i < w - 2; ++i)
        putchar(' ');
    putchar(c);
    putchar('\n');
}

/* write the final line */
for (i = 0; i < w; ++i)
    putchar(c);
putchar('\n');