Yes it is possible:
printf("\n| %.*s | %8s | %8s |", MAX, "Nome", "Salario", "Idade");
The secret is the .*
. It is a parameter for the string formatting. Note that as is the first parameter the MAX
must be the first on the list, that is, it follows the same logic as the other normal parameters of printf()
. With the .*
it is a limiter of the maximum characters that will be displayed which is what I understood you want. I still put options for you to use the parameter as the minimum of characters that should be displayed using only the *
.
Read to documentation for more details. Especially about "The field width". And a summary on the existing formatting parameters.
#include <stdio.h>
int main(void) {
int max = 30;
printf("\n| %*s | %8s | %8s |", max, "Nome", "Salario", "Idade");
printf("\n| %.*s | %8s | %8s |", max, "Nome", "Salario", "Idade");
max = 3;
printf("\n| %*s | %8s | %8s |", max, "Nome", "Salario", "Idade");
printf("\n| %.*s | %8s | %8s |", max, "Nome", "Salario", "Idade");
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
This way it prints "Name" with the MAX character limit?
– Antony Alkmim
Exactly. It’s just a limit.
– Maniero
Thanks Bigown, that was exactly my need. out of great help
– Guilherme Lautert