Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Justifying output stream in C++

Tags:

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.

like image 367
Matt Dunbar Avatar asked Mar 05 '11 04:03

Matt Dunbar


People also ask

How do you justify text to the right in C++?

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.

How do you justify output in C++?

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.

What is left justified in C++?

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.

What does right do in C++?

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.


1 Answers

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; } 
like image 122
florin Avatar answered Sep 20 '22 23:09

florin