如何打印N个相同的字符

How to print N identical characters

本文关键字:字符 何打印 打印      更新时间:2023-10-16

有这样一个程序

#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-in=15i >= 7时将为负,因为n/2 == 7。因此,您的程序需要重新设计。

编辑:

只需更改一行:

   cout << string(n-i-1, ' ') << string(i*2+1, 42) << endl;