Ask Your Question
0

How can I format the output of cout to be aligned with the columns of a table?

asked 2023-07-21 03:16:48 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-21 03:18:01 +0000

plato gravatar image

There are different ways to format the output of cout to be aligned with the columns of a table, but one approach is to use the setw() function from the iomanip header. Here's an example:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout << std::setw(10) << "Column 1";
    std::cout << std::setw(10) << "Column 2";
    std::cout << std::setw(10) << "Column 3" << std::endl;

    std::cout << std::setw(10) << 1;
    std::cout << std::setw(10) << 2;
    std::cout << std::setw(10) << 3 << std::endl;

    std::cout << std::setw(10) << 111;
    std::cout << std::setw(10) << 222;
    std::cout << std::setw(10) << 333 << std::endl;

    return 0;
}

In this example, the setw() function sets the width of the next output field to a fixed value. The first cout statement specifies the column headers with a width of 10 characters each. The following cout statements specify the values for each column also with a width of 10 characters each. By using the setw() function, the output will be aligned with the columns of a table. The output of this example will be:

  Column 1 Column 2  Column 3
         1         2         3
       111       222       333
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-21 03:16:48 +0000

Seen: 13 times

Last updated: Jul 21 '23