D
D
dandropov952018-08-17 15:37:17
C++ / C#
dandropov95, 2018-08-17 15:37:17

How to dynamically specify field length for output in printf?

You need to ask the user for a name and display it in a field that is 3 characters longer than the length of the entered name.
How to dynamically substitute a value in a format string? Or how to translate a number into a string so that you can insert the value as a string. So it looks like it can be done.
printf("%" ЗНАЧЕНИЕ ДЛИНЫ "s", name);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
res2001, 2018-08-17
@dandropov95

1. You can just form a valid C string by adding a null character at the end, then printf will work correctly with the %s format specifier.
2.If you don't have a string, but a byte array (that is, there is no terminating null character), then you can do this: printf("%.*s", (int)len, str)

V
Vladimir Dubrovin, 2018-08-17
@z3apa3a

Use snprintf to generate a format string

char fsbuf[256];
...
snprintf(fsbuf, sizeof(fsbuf), "%%%ds", (int)strlen(name)+3);
printf(fsbus, name);

but something tells me that you formulated the problem for yourself incorrectly.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question