Reputation: 410
I'm working on prefixing of a string for example : com
should give me c
co
com
.
I know to print a character in this was printf("%.5s",string)
to print the first five values. I want to do this in a loop instead of 5 how can I replace it with i
which is a incrementing value,something like this printf("%.is",string)
. how can I obtain this?
Upvotes: 0
Views: 5117
Reputation: 106012
Try this:
char s[] = "com";
for(size_t i = 1; i <= strlen(s); i++)
{
for(int j = 0; j < i; j++)
printf("%c", s[j]);
printf(" ");
}
Upvotes: 0
Reputation: 53006
This is the simplest way of achieving what you want.
printf("%.*s\n", i, string);
If you want to generate the format string, you can do it too
char format[100]; /* the size should be estimated by you */
snprintf(format, sizeof(format), "%%.%ds", i);
printf(format, string)
check the snprintf()
return value to ensure that the string was not truncated, if you choos a reasonable size for the format string it will be unlikely, but you should check anyway.
Above, the format specifier means
"%"
"."
"%d"
"s"
so the resulting string will be the format string you need to pass to printf()
.
Upvotes: 1
Reputation: 29126
In printf
format specifiers, all field widths (before the dot) and precisions (after the dot) can be given as asterisk *
. For each asterisk, there must be one additional int
argument before the printed object.
So, for your problem:
printf("%.*s", i, string);
Note that the additional parameter must be an int
, so if you have another integer type, you should cast it:
size_t len = strlen(len);
if (len > 2) printf("%.*s", (int) (len - 2), string);
Upvotes: 5