I am trying to align these strings with their respective indexes. The strings look like this:
char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};
and my output looks like this:
Fred 0
Augustine 1
Bob 2
Lenny 3
Ricardo 4
But I am after some thing like this:
Fred 0
Augustine 1
Bob 2
Lenny 3
Ricardo 4
Whereby the indexes are aligned the same. I'm just trying to make it more readable. This is what my code looks like so far:
#include <stdio.h>
#include <stdlib.h>
int
main(void) {
int i;
char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};
for (i = 0; i < 5; i++) {
printf("%s %d\n", mystrings[i], i);
}
return 0;
}
Is there a way I can do this? Like compare the indexes with the longest string, and then make the spaces for the integers like that?
Extra loop to calculate the max width, then use the *
printf flag to take the width from an argument (which is multiplied by -1 to cause left justification)
char *mystrings[] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};
int width = 0;
for (int i = 0; i < sizeof(mystrings)/sizeof(char*); i++) {
width = strlen(mystrings[i]) > width? strlen(mystrings[i]) : width;
}
for (int i = 0; i < sizeof(mystrings)/sizeof(char*); i++) {
printf("%*s %d\n", -1 * width, mystrings[i], i);
}
You need to specify a width for the string in the format specification.
Then, you need to use the -
specifier to indicate that you want the output to be left justified.
Using
printf("%-10s %d\n", mystrings[i], i);
will use 10 characters for mystrings[i]
and will left justify the output.
Hard coding a number like that will be a problem if you don't know the lengths of the strings. To make your program a bit robust, you can compute the maximum length of the strings and then compute the format string from that.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXSIZE 5
int main(void) {
int i;
char *mystrings[MAXSIZE] = {"Fred", "Augustine", "Bob", "Lenny", "Ricardo"};
int maxLen = 0;
for (i = 0; i < MAXSIZE; i++) {
int len = strlen(mystrings[i]);
maxLen = (len > maxLen) ? len : maxLen;
}
char formatString[50];
sprintf(formatString, "%%-%ds %%d\n", maxLen + 1);
for (i = 0; i < MAXSIZE; i++) {
printf(formatString, mystrings[i], i);
}
return 0;
}
Output
Fred 0
Augustine 1
Bob 2
Lenny 3
Ricardo 4
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With