22

I'm working in C++. I'm given a 10 digit string (char array) that may or may not have 3 dashes in it (making it up to 13 characters). Is there a built in way with the stream to right justify it?

How would I go about printing to the stream right justified? Is there a built in function/way to do this, or do I need to pad 3 spaces into the beginning of the character array?

I'm dealing with ostream to be specific, not sure if that matters.

Matt Dunbar
  • 890
  • 3
  • 10
  • 21

3 Answers3

38

You need to use std::setw in conjunction with std::right.

#include <iostream>
#include <iomanip>

int main(void)
{
   std::cout << std::right << std::setw(13) << "foobar" << std::endl;
   return 0;
}
florin
  • 13,648
  • 6
  • 42
  • 47
  • 5
    Note: It is *important* that you do the `<< right << setw(13)` right before the thing you want to format. I.e. if you're doing `cout << "added " << 5 << " files" << endl;`, you can't just do `cout << right << setw(13) << "added " ...` at the start. You *must* do it right before the number, at least on MacOS X. – uliwitness Aug 10 '15 at 10:08
8

Yes. You can use setw() to set the width. The default justification is right-justified, and the default padding is space, so this will add spaces to the left.

stream << setw(13) << yourString

See: setw(). You'll need to include <iomanip>.

NullUserException
  • 81,190
  • 27
  • 202
  • 228
6

See "setw" and "right" in your favorite C++ (iostream) reference for further details:

 cout << setw(13) << right << your_string;
Prasoon Saurav
  • 88,492
  • 46
  • 234
  • 343
Jollymorphic
  • 3,470
  • 15
  • 16