Reputation: 121
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?
Upvotes: 12
Views: 28021
Reputation: 91
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/
Upvotes: 9
Reputation:
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;
}
Upvotes: 6