inceon
inceon

Reputation: 5

How to print N identical characters

There is such a program

#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;
}

But in the process, it throws an exception. What are the ways to get rid of it or to write a program on another.

      *
     ***
    *****
   *******
  *********
 ***********
*************
terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create

Upvotes: 0

Views: 202

Answers (1)

VolAnd
VolAnd

Reputation: 6407

n/2-1-i will be negative when n=15 and i >= 7, because n/2 == 7. So a redesign is needed for your program.

EDIT:

Just one line to change:

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

Upvotes: 2

Related Questions