Concatenate string with int in printf

Asked

Viewed 426 times

3

It is possible to do this in C:

int MAX = 30;

printf("\n| %".MAX."s | %8s | %8s |", "Nome", "Salario", "Idade");
printf("\n| %".MAX."s | %8.2f | %8d |", pessoa[i].nome, pessoa[i].salario, pessoa[i].idade);

Note the MAX among the strings to delimit the alignment.

1 answer

5


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?

  • Exactly. It’s just a limit.

  • Thanks Bigown, that was exactly my need. out of great help

Browser other questions tagged

You are not signed in. Login or sign up in order to post.