当打印cout时, [英] C++ alignment when printing cout <<

查看:126
本文介绍了当打印cout时,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用cout进行priting时,有没有办法对齐文本?

Is there a way to align text when priting using 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


推荐答案

ISO C ++标准方法到 #include< iomanip> 并使用io操作符,例如 std :: setw 。然而,这说,这些io操纵器是一个真正的痛苦,甚至使用文本,并且几乎不可用于格式化数字(我假设你想要你的美元金额排列在十进制,有正确的有效数字的数量等。)。即使只是纯文本标签,代码将在第一行的第一部分看起来像这样:

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...

如果您能够使用 Boost库,请运行(不要步行),然后使用 Boost.Format 库。它完全兼容标准的iostreams,它给你所有的好处,使用printf / Posix格式化字符串轻松格式化,但不失去iostreams本身的任何权力和便利。例如,前两行的第一部分将类似于:

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;

这篇关于当打印cout时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆