Home > database >  best way to print a list in c?
best way to print a list in c?

Time:12-17

so I'm trying to print a list of items, here's my simple code

#include<stdio.h>


int main(void)
{
    int number = 1;
    char code[20] = "BIC1";
    char item[20] = "books";
    int amount = 2;
    int price = 2000;
    printf("|%-40s|\n", "Details");
    printf("|%d. %s - %s - %d pcs - $ %d |" , number, code, item, amount, price);
}

is there a way so I can match the right side | automatically, cause that code would only produce enter image description here

instead of this

enter image description here

CodePudding user response:

Use snprintf to "print" the data into a separate string, then use print that string using the same format as the header.

Something like:

char data[256];  // No need to skimp on space
snprintf(data, sizeof data, "%d. %s - %s - %d pcs - $ %d" , number, code, item, amount, price);

printf("|%-40s|\n", "Details");
printf("|%-40s|\n", data);

As an alternative you could output each column using a fixed width, and make sure that the width matches that of the header output.

CodePudding user response:

is there a way so I can match the right side | automatically (?)

Note the length of the first print's text up to the '|'.

Use that to pad the 2nd line's '|'.

int main(void) {
  int number = 1;
  char code[20] = "BIC1";
  char item[20] = "books";
  int amount = 2;
  int price = 2000;

  int length1 = printf("|%-40s", "Details");
  printf("|\n");

  int length2 = printf("|%d. %s - %s - %d pcs - $ %d" , number, code, item, amount, price);
  int padding = length1 - length2;
  printf("%*s|\n", padding < 0 ? 0 : padding, "");
}

Output

|Details                                 |
|1. BIC1 - books - 2 pcs - $ 2000        |

Tighter code exist, yet the above is more illustrative.

  •  Tags:  
  • c
  • Related