Markus Fürst Markus Fürst - 11 days ago 7
C++ Question

C++ columns, line up perfectly

So I'm trying to write this code that displays ASCII code in perfect columns, but the columns are perfectly lined up right know. What am I doing wrong?

#include <iostream> // cout
#include <iomanip> // setw

using namespace std;
int main ()
{
int a;
for(a=32;a<=255;++a)
{
cout << a << setw(2) <<static_cast<char>(a)<< setw(20);
}

return 0;
}


This is how I want it to look like,
http://www.asciitable.com/index/extend.gif

Answer

Try this:

#include <iostream>   // cout
#include <iomanip>    // setw

using namespace std;
int main()
{
    int a;
    int count = 0;
    for (a = 32; a <= 255; ++a)
    {
        cout << a << setw(2) << static_cast<char>(a);
        if (count != 3)
        {
            cout << setw(20);
            count++;
        }
        else
        {
            count = 0;
            cout << endl;
        }
    }
    cout << endl;

    return 0;
}

PS: if you want to have more columns that are equally long try to change this if (count != 3) and this cout << setw(20); to something like if (count != 6) and cout << setw(9);