Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing formatted string in C

So I have a string of length 10. And I want to print the letters from 4-6[including both], and I want to span the output over a particular length L, with the digits being placed on the right side.

For eg

If I had the original String 123456789, then the following code should display in the subsequent manner.

printf(Original);
printf(from 4-6, over 5 spaces)

Output:

123456789
  456

That is 456 is spread over 5 spaces and indented right.

How do I do it in C?

EDIT 1 : What if my width is not constant, and I have a variable, that dictates, the width. Similarly for the length of the substring is a variable. Any way of doing it now?

Can I do something like

printf("%%d.%ds",width,precision,expression);
like image 217
Kraken Avatar asked Dec 15 '22 08:12

Kraken


1 Answers

Very direct:

printf("%5.3s\n", Original + 4);
         ^ ^
         | |
         | +--- precision, causes only 3 characters to be printed
         |
         +----- field width, sets total width of printed item

Since right-adjusting is the default, you get the desired output.

The precision "saves" us from having to extract the three characters into a properly terminated string of their own, very handy.

You can use dynamic values for either precision or field width (or both, of course) by specifying the width as * and passing an int argument:

const int width = 5, precision = 3;
printf("%*.*s\n", width, precision, Original + 4);
like image 73
unwind Avatar answered Jan 10 '23 11:01

unwind