'Hackerrank Staircase in C++

I am trying to solve this problem in C++ using std::cout and using setw and setfill

my original code was this:

void staircase(int n) {
    for(int i = 0; i < n; i++) {
        cout << setfill(' ') << setw(n-(i+1));
        cout << setfill('#') << setw(i+1) << '#'<< endl;
    }
}

This doesn't print out the spaces that right aligns the # character. I added this to the output buffer cout << setfill(' ') << setw(n-(i+1)) << ' '; and it prints the space character, but for the last line it prints a space character.

Is there something in setw that I am missing?

c++


Solution 1:[1]

You need to print out something or the second setfill and setw replace the first. eg:

#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

void staircase(int n) {
    for(int i = 0; i < n; i++) {
        cout << setfill(' ') << setw(n-(i+1)) << '|';
        cout << setfill('#') << setw(i+1) << '#'<< endl;
    }
}

int main(void)
{
    staircase(4);
}

prints out

  |#
 |##
|###
|####

All you need to do is print out something more useful than |, like a #, and fix up your alignment math.

Solution 2:[2]

A good solution for this problem is to use default constructor of string class like this:

for (int i = 0; i < n; i++)
{
        int j = i+1;
        string spaces(n-j, ' ');
        string hashes(j, '#');
        cout << spaces + hashes << endl;

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user4581301
Solution 2 Mohamed Helmy