How to set a fixed width with cout?
Asked Answered
S

2

12

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?

Susansusana answered 18/9, 2014 at 16:39 Comment(1)
Setting a fixed with for the second and third column won't be of much use if you don't also do so for the first.Corporative
T
8

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;
}

https://www.cplusplus.com/reference/iomanip/setw/

Troublous answered 2/3, 2022 at 5:55 Comment(1)
Please provide some context to the code.Thorncombe
L
6

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;
 }
Lanctot answered 18/9, 2014 at 16:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.