1

下面的代码打印一个带有用户输入的整数的框。我需要使它空心以仅显示框的第一行和最后一行的全长。像宽度 = 5 高度 = 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;
   }
}

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

4

2 回答 2

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
**********
*        *
*        *
*        *
*        *
*        *
**********
于 2013-11-04T01:16:57.400 回答
0

if在行中添加一个cout << character。如果我们不在第一行或第一列,输出一个空格而不是字符。

于 2013-11-04T01:04:30.330 回答