如何在 for 循环中设置异常

How to make exception in for loop?

本文关键字:设置 异常 循环 for      更新时间:2023-10-16

下面的代码打印了一个框,其中包含用户输入的中间器。我需要使其空心以仅显示框的第一行和最后一行的全长。类似宽度 = 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;
   }
}

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

我认为

您可以测试您是在第一行还是最后一行,以及第一列还是最后一列。

例:

#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
**********
*        *
*        *
*        *
*        *
*        *
**********

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