简体   繁体   中英

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);

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);
#include <stdio.h>

int main(void)
{
    char *original = "123456789";

    printf("%5.3s\n", original + 3);
    return 0;
}

EDIT:

if you want a precision based on a variable:

int prec = 2;

printf("%5.*s\n", prec, original + 3);

... same for width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM