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.
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.
Use the printf Function to Right Justify Output in C++ As a result, each line is 20 character wide, and since the number is positive, the filling chars are appended from the left. Alternatively, we can insert a negative integer in the format specifier to fill characters on the right side, justifying output left.
C++ manipulator left function is used to set the adjustfield format flag for the str stream to left. When we set adjustfiled to left, the output is padded to the field width by inserting fill characters at the end, effectively adjusting the field to the left.
The right() method of stream manipulators in C++ is used to set the adjustfield format flag for the specified str stream. This flag sets the adjustfield to right. It means that the number in the output will be padded to the field width by inserting fill characters at the start.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With