下面的代码打印一个包含用户输入的整数的框。我需要让它空心,只显示盒子的第一行和最后一行的全长。像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;
}
}
我不知道如何更改宽度的循环条件以使其工作。
答案 0 :(得分:2)
我认为你可以测试你是在第一行还是最后一行,第一列还是最后一列。
示例:
#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
**********
* *
* *
* *
* *
* *
**********
答案 1 :(得分:0)
将if
添加到cout << character
行。如果我们不在第一行或第一列,则输出空格而不是字符。