0

I need the following output by setw and setfill: aaa______aaa (These underscores represent spacing) (No spaces allowed in code) Link also attached

#include<iostream>
#include<iomanip>
using namespace std;
int main()
   { char input=0;
    cout << "Enter the desired character for pattern : "<<endl;
    cin >> input;
    cout << setw(3) << setfill(input) << input
         <<setw(10) << setfill(' ')  setw(2)
         << setfill(input)<< input<<endl;
}

By the above mentioned code I do not get my desired output. The setfill works for the first time and then doesnt work for spaces and the next repitition. Output by this code is: aaaaaa (No spaces are outputted)

If we consider the following code:

#include<iostream>
#include<iomanip>
using namespace std;
int main()
   { 
    char input=0;
    cout << "Enter the desired character for pattern : "<<endl;
    cin >> input;
    cout << setw(3) << setfill(input) << input 
         <<setw(10) << setfill(' ')
         << input << input <<input <<endl;
}

This works perfectly but I don't want to repeat input 3 times at the end by writing it three times, I want to use setfill. What to do?

The required output if input is *

Toby Speight
  • 27,591
  • 48
  • 66
  • 103

2 Answers2

0

You need to actually print something for the width and fill to be used:

#include <iomanip>
#include <iostream>

int main()
{
    char input = 'a';
    std::cout << std::setw(3)  << std::setfill(input) << ""
              << std::setw(10) << std::setfill(' ') << ""
              << std::setw(2)  << std::setfill(input) << ""
              << '\n';
}
aaa          aa

Note that the empty string here counts as "something" to be formatted.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
0

Your problem is in this line 2 of cout: <<setw(10) << setfill(' ') setw(2), notice that you are using two times setw() without printing anything to screen. You can use something like this for second line:

<< setw(10) << setfill(' ') << "" << setw(3)

this make cout like:

cout << setw(3) << setfill(input) << input
        << setw(10) << setfill(' ') << "" << setw(3)
        << setfill(input) << input << endl;