cout: consistent spacing with looped cout statements
c++, cout, formatting
Solution
Use `std::setw()`, `std::left` and `std::right`.
#include <iostream>
#include <iomanip>
void printNumber(int x) {
std::cout << "X:" << std::setw(6) << x << ":X\n";
}
void printStuff() {
printNumber(528);
printNumber(3);
printNumber(73826);
printNumber(37);
}
int main() {
std::cout << "Left-aligned\n";
std::cout << std::left;
printStuff();
std::cout << "Right-aligned\n";
std::cout << std::right;
printStuff();
}
Output:
Left-aligned
X:528 :X
X:3 :X
X:73826 :X
X:37 :X
Right-aligned
X: 528:X
X: 3:X
X: 73826:X
X: 37:X
(Demo: http://ideone.com/6IdIc.)
In this example, I've used 6 as the maximum width expected. If you don't know the maximum, you'll either need to do an initial pass through your data to find out, or just use the maximum possible for the data-type you're using (to make this portable, you could use `std::numeric_limits<T>::max`).
Problem
I often run into a situation where I want to print a 2d array to screen or file. My standard approach is this: ``` for(int q=0; q<x; q++) { cout << "\n"; for(int w=0; w<y; w++) cout << number[q][w] << "\t"; } ``` However, when the elements of `number` vary in length, this typically leads to the columns not being aligned properly. How can I add the correct amount of whitespace after (or before) each number to make the columns line up?