gpt4 book ai didi

c++ - 如何在for循环中产生异常?

转载 作者:行者123 更新时间:2023-11-30 04:12:37 27 4
gpt4 key购买 nike

下面的代码打印一个框,其中包含用户输入的整数。我需要将其设为空心以仅显示框的第一行和最后一行的全长。比如 width = 5 height = 4

示例输出:

00000
0 0
0 0
00000

来源:

int main () 
{
int height;
int width;
int count;
int hcount;
string character;

cout << "input width" << endl;
cin >> width;
cout << "input height" << endl;
cin >> height;
cout << "input character" << endl;
cin >> character;

for (hcount = 0; hcount < height; hcount++)
{
for (count = 0 ; count < width; count++)
cout << character;
cout << endl;
}
}

我不知道如何更改宽度的循环条件以使其工作。

最佳答案

我认为你可以测试你是在第一行还是最后一行,第一列还是最后一列。

例子:

#include <string>
#include <iostream>

int main ()
{
using namespace std; // not recommended

int height;
int width;
string character;

cout << "input width" << endl;
cin >> width;
cout << "input height" << endl;
cin >> height;
cout << "input character" << endl;
cin >> character;

for (int i = 0; i < height; i++)
{
// Test whether we are in first or last row
std::string interior_filler = " ";
if (i == 0 || i == height - 1)
{
interior_filler = character;
}

for (int j = 0; j < width; j++)
{
// Test whether are in first or last column
if (j == 0 || j == width -1)
{
cout << character;
} else {
cout << interior_filler;
}
}
// Row is complete.
cout << std::endl;
}
}

这是输出:

$ ./a.out 
input width
10
input height
7
input character
*
OUTPUT
**********
* *
* *
* *
* *
* *
**********

关于c++ - 如何在for循环中产生异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19760158/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com