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

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...