如何打印N个相同的字符
How to print N identical characters
有这样一个程序
#include <bits/stdc++.h>
using std::cout;
using std::endl;
using std::string;
int main()
{
const int n = 15;
for(int i=0;i<n;i++)
cout << string(n/2-1-i, ' ') << string(i*2+1, 42) << endl;
return 0;
}
但在这个过程中,它抛出了一个异常。有什么方法可以摆脱它,或者在另一个程序上编写程序。
*
***
*****
*******
*********
***********
*************
terminate called after throwing an instance of 'std::length_error'
what(): basic_string::_S_create
n/2-1-i
在n=15
和i >= 7
时将为负,因为n/2 == 7
。因此,您的程序需要重新设计。
编辑:
只需更改一行:
cout << string(n-i-1, ' ') << string(i*2+1, 42) << endl;
相关文章:
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 打印第二列时的2d字符矢量打印空间
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何打印 2D 字符数组C++
- 打印十六进制字符
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 将浮点数转换为无符号字符数组并打印出来
- 打印从 0 到 255 的所有 ASCII 字符
- 如何让字符数组在一行而不是多行中打印出来?
- 无符号字符打印其 ASCII 值
- 打印字符数组地址的正确方法
- 在 CPP 中打印具有重复项的选定长度字符的所有排列
- 为什么C++将无符号字符值打印为负数?
- 循环中的 Cout 不会按定义的字符逐个打印字符
- 托架返回,导致COUT覆盖字符并打印出订单
- 创建临时字符*并打印到它的正确方法是什么
- 找到文本文件中的最后一行,选择前10个字符并打印到一个新文件中
- 字符串中的阿拉伯字符未打印
- 退格字符在打印到文件时不工作
- 冲刺'+'字符不打印