Concatenate string with int in printf

3

You can 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 between strings to delimit the alignment.

    
asked by anonymous 06.11.2014 / 00:32

1 answer

5

Yes it is possible:

printf("\n| %.*s | %8s | %8s |", MAX, "Nome", "Salario", "Idade");

The secret is .* . It is a parameter to the string formatting. Note that since it is the first parameter the MAX must be the first one in the list, that is, it follows the same logic as the other normal parameters of printf . With .* it is a limiter of the maximum characters that will be displayed which is what I understood you want. I have still put options to use the parameter as the minimum of characters that should be displayed using only * .

Read the documentation for more details. Especially on "The field width". And a summary about 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");
}

See running on ideone . And in Coding Ground . Also I placed GitHub for future reference .

    
06.11.2014 / 00:42