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?
Use
std::setw(),std::leftandstd::right.Output:
(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).