Home > Software design >  how can I make the output look like a table?
how can I make the output look like a table?

Time:09-24

I wrote a program that prints all Ascii characters in different representations, but I want the output to be more like a table than the current one

so this is my code

//method to convert decimal to base 2 (binary)
#include <stdio.h> 
void decToBinary(int n) 
{
  int binaryNumber[32];
  int i = 0;
  while (n > 0)                                 
  {
      binaryNumber[i] = n % 2;
      n = n / 2;
      i  ;
  }
  for (int j = i - 1; j >= 0; j--)
      printf_s("%d",binaryNumber[j]);
}
//*...................................//*

//print Ascii using for loop with multi representations
int main() 
{
int n; 

printf_s("\n       deci  hex   oct  binary     characters \n"); 

for(n = 0; n < 256; n  )
{
printf_s("\n    ]    %2x    o\t", n, n, n); 
decToBinary(n);
printf_s("c", n);

}

return 0; 

}

and this is the output I get

and I want the output to be more like this but with every 20 lines not 31

and if you have any other suggestions please tell me

.

CodePudding user response:

make the output look like a table?

Use a width.

Convert binary to a string.

Use '\n' at the end.

Some columns left out for OP's completion

#include <stdio.h>

// This code still needs more work to handle values <= 0
char* int2Binary(char *binaryNumber, int n) {
  int i = 32;
  binaryNumber[i] = '\0';  // Set null character
  while (n > 0) {
    binaryNumber[--i] = (char) ((n % 2)   '0');
    n = n / 2;
  }
  return &binaryNumber[i];
}

int main() {
  int width1 = 11;
  int width2 = 4;
  int width3 = 8;
  printf("<%*s %*s %*s>\n", width1, "deci", width2, "hex", width3, "binary");
  for (int n = 1; n <= 10; n  ) {
    char buf[34];
    printf("<%*.5d %*.2x %*s>\n", //
        width1, n, width2, n, width3, int2Binary(buf, n));
  }
}

Output

<       deci  hex   binary>
<      00001   01        1>
<      00002   02       10>
<      00003   03       11>
<      00004   04      100>
<      00005   05      101>
<      00006   06      110>
<      00007   07      111>
<      00008   08     1000>
<      00009   09     1001>
<      00010   0a     1010>

CodePudding user response:

You have this tagged as C and C, while the code posted is clearly C, which complicates answering this question. If you are going to use C , you can use ostream modifiers such as setw() to organize the output. If it is in fact a pure C program, i would reccomend looking into the NCurses library (which is also supported in C )

  •  Tags:  
  • c
  • Related