Reputation: 23
I want to create a tabular display that has a name, ID, course year and GPA and have the spacing in the name and courses to be based on the longest name and course there is
I tried using align specifiers, but it can be hard to just assume that the longest name available would be the same each time the program is run
Upvotes: 0
Views: 35
Reputation:
You will need to iterate through your data to figure out the width of each column:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX(a, b) (a) >= (b) ? (a) : (b)
int main() {
char *data[] = {"what", "is", "the", "secret?" };
size_t w = 0;
for(size_t i = 0; i < sizeof data / sizeof *data; i++) {
size_t tmp = strlen(data[i]);
w = MAX(w, tmp);
}
for(size_t i = 0; i < sizeof data / sizeof *data; i++)
printf("| %*s |\n", (int) w, data[i]);
}
and here is the corresponding output:
| what |
| is |
| the |
| secret? |
Upvotes: 0