Is there a way to specify how many characters of a string to print out using printf()?
The basic way is:
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
The other, often more useful, way is:
printf ("Here are the first %d chars: %.*s\n", 8, 8, "A string that is more than 8 chars");
Here, you specify the length as an int argument to printf(), which treats the '*' in the format as a request to get the length from an argument.
You can also use the notation:
printf ("Here are the first 8 chars: %*.*s\n",
8, 8, "A string that is more than 8 chars");
This is also analogous to the "%8.8s" notation, but again allows you to specify the minimum and maximum lengths at runtime - more realistically in a scenario like:
printf("Data: %*.*s Other info: %d\n", minlen, maxlen, string, info);
The POSIX specification for printf()
defines these mechanisms.
In addition to specify a fixed amount of characters, you can also use *
which means that printf takes the number of characters from an argument:
#include <stdio.h>
int main(int argc, char *argv[])
{
const char hello[] = "Hello world";
printf("message: '%.3s'\n", hello);
printf("message: '%.*s'\n", 3, hello);
printf("message: '%.*s'\n", 5, hello);
return 0;
}
Prints:
message: 'Hel'
message: 'Hel'
message: 'Hello'
printf ("Here are the first 8 chars: %.8s\n", "A string that is more than 8 chars");
%8s would specify a minimum width of 8 characters. You want to truncate at 8, so use %.8s.
If you want to always print exactly 8 characters you could use %8.8s