How to Set a Fixed Width with Cout?

I want to cout a table like output using c++. It should look like this

Passes in Stock : Student Adult
-------------------------------
Spadina               100   200
Bathurst              200   300
Keele                 100   100
Bay                   200   200

yet mine always looks like

Passes in Stock : Student Adult
-------------------------------
Spadina               100   200
Bathurst               200   300
Keele               100   100
Bay               200   200

my code for the output

std::cout << "Passes in Stock : Student Adult" << std::endl;
std::cout << "-------------------------------";

    for (int i = 0; i < numStations; i++) {

        std::cout << std::left << station[i].name;
        std::cout << std::right << std::setw(18) << station[i].student << std::setw(6) << station[i].adult << std::endl;

    }

how can I change it so it looks like the output at the top?

1

2 Answers

For consistent spacing you can store the lengths of the headers in an array.

size_t headerWidths[3] = {
    std::string("Passes in Stock").size(),
    std::string("Student").size(),
    std::string("Adult").size()
};

The things inbetween, such as " : " the space between Student and Adult should be considered extraneous output that you don't factor into the calculation.

for (int i = 0; i < numStations; i++) {

  std::cout << std::left << std::setw(headerWidths[0]) << station[i].name;
  // Spacing between first and second header.
  std::cout << "   ";
  std::cout << std::right << std::setw(headerWidths[1]) << station[i].student 
  // Add space between Student and Adult.
            << " " << std::setw(headerWidths[2]) << station[i].adult << std::endl;
 }

use setw()

// setw example
#include <iostream>     // std::cout, std::endl
#include <iomanip>      // std::setw

int main () {
  std::cout << std::setw(10);
  std::cout << 77 << std::endl;
  return 0;
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest