Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ alignment when printing cout <<

Is there a way to align text when printing using std::cout? I'm using tabs, but when the words are too big they won't be aligned anymore.

Sales Report for September 15, 2010 Artist  Title   Price   Genre   Disc    Sale    Tax Cash Merle   Blue    12.99   Country 4%  12.47   1.01    13.48 Richard Music   8.49    Classical   8%  7.81    0.66    8.47 Paula   Shut    8.49    Classical   8%  7.81    0.72    8.49 
like image 451
user69514 Avatar asked Mar 21 '10 04:03

user69514


People also ask

How do you align prints in C?

You can use printf("%*s", <width>, "a"); to print any text right aligned by variable no. of spaces.

How do you center align text in C++?

You can center the text in C++ by using the std::setw() I/O stream manipulator.

How will you align the output left or right in C programming?

By using justifications in printf statement we can arrange the data in any format. To implement the right justification, insert a minus sign before the width value in the %s character.

How do you left align in C++?

ios manipulators left() function in C++The left() 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 left. It means that the number in the output will be padded to the field width by inserting fill characters at the end.


1 Answers

The ISO C++ standard way to do it is to #include <iomanip> and use io manipulators like std::setw. However, that said, those io manipulators are a real pain to use even for text, and are just about unusable for formatting numbers (I assume you want your dollar amounts to line up on the decimal, have the correct number of significant digits, etc.). Even for just plain text labels, the code will look something like this for the first part of your first line:

// using standard iomanip facilities cout << setw(20) << "Artist"      << setw(20) << "Title"      << setw(8) << "Price"; // ... not going to try to write the numeric formatting... 

If you are able to use the Boost libraries, run (don't walk) and use the Boost.Format library instead. It is fully compatible with the standard iostreams, and it gives you all the goodness for easy formatting with printf/Posix formatting string, but without losing any of the power and convenience of iostreams themselves. For example, the first parts of your first two lines would look something like:

// using Boost.Format cout << format("%-20s %-20s %-8s\n")  % "Artist" % "Title" % "Price"; cout << format("%-20s %-20s %8.2f\n") % "Merle" % "Blue" % 12.99; 
like image 149
Herb Sutter Avatar answered Sep 23 '22 01:09

Herb Sutter