Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

c++ - How do I correctly organize output into columns?

The first thing that comes to my mind is to do a bunch of '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

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

Name    Last Name            Middle initial
Bob     Jones                M
Joe     ReallyLongLastName                T

or

Name    Last Name            Middle initial
Bob     Jones    M
Joe     ReallyLongLastName   T

What else would I need to do?

EDIT: 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use std::setw from <iomanip>

e.g.

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

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

Output:

      This        is         a      test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...