Reputation: 71
I'm new to C and I need to print all ASCII characters in columns (going in order per column and not per row) however the user needs to be able to choose, how many columns are displayed.
I'm able to do it with a specific number of columns, but I can't think of way without writing 255 different printing formats. Here's part of printing function:
int rows = 255/numberOfColumns;
for (i = 0; i <= rows; i++)
{
printf("%3d = %s\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t"
"%3d = %c\t\t\n", i, valorControl, i + 32, i + 32,
i+(32*2), i+(32*2), i+(32*3), i+(32*3), i+(32*4),
i+(32*4), i+(32*5), i+(32*5), i+(32*6), i+(32*6),
i+(32*7), i+(32*7));
Upvotes: 3
Views: 1308
Reputation: 9203
Considering the first %s
as a type instead of %c
, you could write -
int rows = (256+numberOfColumns-1)/numberOfColumns;
for (j=0; j<rows; j++){
for (i=0; i<numberOfColumns; i++){
int character = i*rows+j;
if(character>=256)
break;
printf("%3d = %c\t\t", character, character);
}
printf("\n");
}
The outer loop is the same as the loop in your code (a bit more accurate). The inner loop prints each column with tabs.
Also, you should try to print only printable characters. Even among the printable characters, the characters like \t
and \n
are going to destroy your alignment.
You can do that with -
printf("%3d = %c\t\t",character, isprint(character)?character:'_');
This only prints the printable characters and prints a '_'
for the rest.
Here is the DEMO
Upvotes: 2