26

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
  • 950
  • 3
  • 11
  • 21

4 Answers4

41

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,986
  • 6
  • 46
  • 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
10

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
  • 83,810
  • 28
  • 209
  • 234
6

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

 cout << setw(13) << right << your_string;
Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
Jollymorphic
  • 3,510
  • 16
  • 16
0

Not a unique answer, but an additional "gotcha" that I discovered and is too long for a comment...

All the formatting stuff is only applied once to yourString. Anything additional, like << yourString2 doesn't abide by the same formatting rules. For instance if I want to right-justify two strings and pad 24 asterisks (easier to see) to the left, this doesn't work:

std::ostringstream oss;
std::string h = "hello ";
std::string t = "there";
oss << std::right << std::setw(24) << h << t;
std::cout << oss.str() << std::endl;
// this outputs
******************hello there

That will apply the correct padding to "hello " only (that's 18 asterisks, making the entire width including the trailing space 24 long), and then "there" gets tacked on at the end, making the end result longer than I wanted. Instead, I wanted

*************hello there

Not sure if there's another way (you could simply redo the formatting I'm sure), but I found it easiest to simply combine the two strings into one:

std::ostringstream oss;
std::string h = "hello ";
std::string t = "there";
// + concatenates t onto h, creating one string
oss << std::right << std::setw(24) << h + t;
std::cout << oss.str() << std::endl;
// this outputs
*************hello there

The whole output is 24 long like I wanted.

Demonstration

yano
  • 4,827
  • 2
  • 23
  • 35