0

I have a string s, and I need it to pad up right side of the string with spaces, up to 15 chars. I tried using setw(), but that just adds 15 spaces regardless.

So if s = "aaaaaaaaaaaaaaa" (15 chars), no white space should be added.

If s = "aaa", then 12 white space characters should be added.

Is there a function for this in iomanip?

mpospelov
  • 1,510
  • 1
  • 15
  • 24
  • 2
    Sounds like an XY problem. Why do you want to do this? – NathanOliver Feb 04 '19 at 21:07
  • its just how I have to output my program. It's just a formatting thing when using cout – Thomas Formal Feb 04 '19 at 21:10
  • 1
    Sounds like [this](https://stackoverflow.com/questions/14765155/how-can-i-easily-format-my-data-table-in-c) is really what you want. – NathanOliver Feb 04 '19 at 21:11
  • _"Is there a function for this in iomanip?"_ Just look up [`std::ios_base::width`](https://en.cppreference.com/w/cpp/io/ios_base/width). – πάντα ῥεῖ Feb 04 '19 at 21:13
  • @NathanOliver For those also curious, [XY Problem](https://en.wikipedia.org/wiki/XY_problem) as well as [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) and [90% of the battle is won when we solve the XY Problem in Product Management](https://medium.com/swlh/90-of-the-battle-is-won-when-we-solve-the-xy-problem-in-product-management-5a7aef1fa4fa). – Richard Chambers Feb 04 '19 at 22:17

1 Answers1

0

<iomanip> includes std::setw, which is right-justified by default, but std::left is available too:

std::cout << std::left << std::setw(15) << "foo" << "bar";

Output:

foo            bar

Observe that std::left << std::setw() is required before each output that you want to have padded.

Govind Parmar
  • 20,656
  • 7
  • 53
  • 85