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

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

本文关键字:空心 矩形 创建 输入 何使用 用户 C++      更新时间:2023-10-16

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

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

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

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