table

I have a ASCII codes code:

1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
    for(int x=0;x<=255;x++)
    printf("%4d %c", x, x);
    return 0;
}

but they are all messy , I want to put them into table , but I don't know how
Add a tab between the characters
Add a end of line at the end of each line
printf("%d\t%c\n", x, x);
That will give a single column, though.

If you are OK numbering them in column-major order
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
...
then just print a newline after every N characters. Assuming an 80-column display, and 6 character-wide columns, that's 13 columns per row max. You can adjust that by changing the width of the columns so long as the total number of characters used per row < 80 (because some terminals wrap and some don't, and I think you would prefer a nicely ordered presentation that won't scroll off the top of the terminal).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>

int main()
  {
  int row, col, value;

  for (row = 0; row < 256; row += 13)
    {
    for (col = 0; col < 13; col++)
      {
      value = row + col;
      if (value >= 256) break;
      printf( "%4d %c", value, value );
      }
    printf( "\n" );
    }

  return 0;
  }

That will give you ceil( 256 / 13 ) == 20 rows of ASCII codes (the last row only partially filled --as per line 13).

If, however, you want to arrange codes vertically, in row-major order
0 20 40 60 80 100 120 140 160 180 200 220 240 1 21 41 61 81 101 121 141 161 181 201 221 241 2 22 42 62 ...
...
then you'll have to adjust the inner loop to jump by 20 and the outer loop by just one. (Remember, ceil( 256 / 13 ) == 20.) You'll still have 13 columns by 20 rows, but now the last column will be incomplete (as per line 13 again).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include <stdlib.h>

int main()
  {
  int row, col, value;

  for (row = 0; row < 20; row++)
    {
    for (col = 0; col < (20 * 13); col += 20)
      {
      value = row + col;
      if (value >= 256) break;
      printf( "%4d %c", value, value );
      }
    printf( "\n" );
    }

  return 0;
  }

Hope this helps.

Disclaimer: untested code. Errors may have happened.

BTW, your code mixes C and C++. While it is OK to do that, you should typically avoid C I/O when programming in C++. You can do all the same stuff and more with the std::iostream.
In any case, the above examples are in C.

[edit] Here's that printf() in C++:
1
2
3
4
5
6
7
8
9
10
#include <iomanip>
#include <iostream>
using namespace std;

int main()
  {
  int value = 65;
  cout << setw( 4 ) << right << value << ' ' << (char)value;
  return 0;
  }
Last edited on
ok , thank you , that helped me.
Topic archived. No new replies allowed.