-
Adding dynamic spaces
Is there a way to add a number of spaces to the output? What I am trying to do is line up names and numbers without them everywhere. So what I was thinking was find the biggest string and then add spaces accordingly to that string. How would I go about this?
-
Well, check the lenght of the string by calling the strlen() function, and than make the calcs and run a loop to start printing the spaces...
-
Instead of adding spaces, you could use the field width specifier.
Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
const char *text[] =
{
"a string",
"another string",
"the longest string",
"a shorter string",
};
size_t i, length [ sizeof(text)/sizeof(*text) ] = {0}, longest = 0;
/* find the longest string */
for(i = 0; i < sizeof(text)/sizeof(*text); ++i)
{
length[i] = strlen(text[i]);
if(length[i] > longest)
{
longest = length[i];
}
}
/* specify the field width as the length of the longest string */
printf("%-*s %s\n", (int)longest, "text", "length");
for(i = 0; i < sizeof(text)/sizeof(*text); ++i)
{
printf("%-*s %lu\n", (int)longest, text[i], (unsigned long)length[i]);
}
return 0;
}
/* my output
text length
a string 8
another string 14
the longest string 18
a shorter string 16
*/
-
I have to admit, I am still an amatuer at this C programming, and while I was using your example I have run into a couple problems, Dave.
Basically, this part:
printf("%-*s %s\n", (int)longest, "text", "length");
Could explain to me how that works, maybe then I will understand what I am doing wrong.
-
>>printf("%-*s %s\n", (int)longest, "text", "length");
For this:
%-*s
The field is a string (%s), the minus sign means left aligned, the * means the length of the field is denoted by the value of the corresponding variable in the subsequent parameters ("longest" in this case). If the length was known at compile time, you would write it like this:
%-10s
for a 10 byte width field.
For this:
(int)longest
the variable longest is of type size_t. In order to conform with the requirements of printf(), it must be cast to an int. This does run the risk of changing the value of the number, as size_t variables can hold a larger number than an int (in general terms), but in this example a high value is unlikely to occur.
Another example to help (maybe!):
Code:
#include <stdio.h>
int main(void)
{
const char *myword = "abcd";
printf (">%-20s<\n", myword);
printf (">%20s<\n", myword);
printf (">%-*s<\n", 20, myword);
printf (">%-.2s<\n", myword);
return 0;
}
/*
Output
>abcd <
> abcd<
>abcd <
>ab<
*
*/
-