如何在 for 循环中设置异常
How to make exception in for loop?
下面的代码打印了一个框,其中包含用户输入的中间器。我需要使其空心以仅显示框的第一行和最后一行的全长。类似宽度 = 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
。如果我们不在第一行或第一列中,则输出一个空格而不是字符。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 在C++/Linux中设置单调时钟的一些技巧
- 处理多个异常集合的C++方法
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 我在c++代码中生成了一个运行时#3异常
- 每当设置了某些数学errno值时,如何引发异常
- std::locale 向"en_US.UTF-8"区域设置抛出runtime_error异常
- 在 Arraydeque 中设置异常不会停止执行
- C++设置"blank"或重置 ifstrean (ios) 的异常掩码
- 如何在 Windows 异常处理程序中设置 MMX 寄存器以模拟不受支持的 3DNow! 说明
- std::设置擦除复杂性异常
- 为什么 getline() 在异常掩码未设置为 eofbit 时抛出'std::ios_base::failure'?
- C++ - 运行 Moses 解码器时区域设置名称无效异常
- 尝试将构造函数设置为 0 - c++ 的未处理异常
- emscripten + sdl = 抛出异常:类型错误:无法设置未定义的属性'widthNative'
- 首次机会异常设置检查列表视图中的状态
- 未设置变量并返回异常数字
- 如何在 for 循环中设置异常
- c++如何设置更严格的异常(错误)规则
- 抛出异常是否影响errno或设置最后错误码