如何正确地将输出组织成列? [英] How do I correctly organize output into columns?

查看:139
本文介绍了如何正确地将输出组织成列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想到的第一件事是做一堆\t的,但是如果任何单词比任何其他单词长出几个字符,这将导致单词不对齐。

The first thing that comes to my mind is to do a bunch of \t's, but that would cause words to be misaligned if any word is longer than any other word by a few characters.

例如,我想要一些类似的东西:

For example, I would like to have something like:

Name    Last Name            Middle initial
Bob     Jones                M
Joe     ReallyLongLastName   T

而是仅包含\t 在我的cout语句中,我只能设法获得

Instead, by including only "\t"'s in my cout statement I can only manage to get

Name    Last Name            Middle initial
Bob     Jones                M
Joe     ReallyLongLastName                T

Name    Last Name            Middle initial
Bob     Jones    M
Joe     ReallyLongLastName   T

我还需要做什么?

编辑:所以我应该首先计算每一列的最大宽度,然后相应地添加填充空间。但是如何,以及用什么功能,我可以这样做吗?

So I get that I should first count the maximum width of each column I want displayed, and then adding padding spaces accordingly. But how, and with what functions, can I go about doing this? Should I simply count the number of chars in a string and then go from there?

推荐答案

使用< iomanip>的//en.cppreference.com/w/cpp/io/manip/setw> std :: setw ;

例如

using std::cout;
using std::setw;

cout << setw(10) << "This" <<
        setw(10) << "is" <<
        setw(10) << "a" <<
        setw(10) << "test" << '\n';

输出:

      This        is         a      test

这篇关于如何正确地将输出组织成列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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