As mentioned before in the comments, you need to ask std::cout
for the correct width before outputting the value, and you need to have a means to output a new line, when you have a certain number of columns. So here is just a small edit to your code (this will have numbers increasing in the row, if you want the values to increase in a column instead of a row, you need to do a bit more math or instead of outputting values directly, have them appended to a string for each line, and then output the values at the end. I'll add the first solution to the end of this answer, since the row-increment answer was already given by someone else :-) ):
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int nocols = 5; // number of columns that you want
for (int a = 32; a < 256; ++a)
{
cout << setw(3) << a << setw(20) << static_cast<char>(a);
if (!((a - 31) % nocols))
cout << endl;
}
return 0;
}
Here is a go at column-increment format:
int nocols = 8; // number of columns that you want
int norows = 1 + (256 - 32 - 1) / nocols; // number of rows
for (int row = 0; row < norows; ++row)
{
for (int col = 0; col < nocols; ++col)
{
int ch = 32 + norows * col + row;
if (ch < 256)
cout << setw(3) << ch << setw(10) << static_cast<char>(ch) << ' ';
}
cout << endl;
}