C++如何用用户输入创建一个空心box/rectangle?

C++ How to create a hollow box/rectangle with user input?

我目前正在做一个项目,系统会提示用户输入高度、宽度和他们想要用于其框的字符。我必须使用 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;

}

这是写空心盒子的代码。 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');

可以写在嵌套的for循环中:

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