Print formatted string in C

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

For instance,

If I had the original String 123456789 , then the following code should display as follows.

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

Output:

 123456789 456 

This 456 spreads over 5 spaces and is indented to the right.

How to do it in C?

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

Can i do something like

 printf("%%d.%ds",width,precision,expression); 
+4
source share
2 answers

Very straightforward:

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

Since the right setting is the default, you get the desired result.

Accuracy saves us from having to extract three characters into a correctly completed line, which is very convenient.

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

 const int width = 5, precision = 3; printf("%*.*s\n", width, precision, Original + 4); 
+7
source
 #include <stdio.h> int main(void) { char *original = "123456789"; printf("%5.3s\n", original + 3); return 0; } 

EDIT:

if you need variable based precision:

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

... same for width

+5
source

Source: https://habr.com/ru/post/1490679/


All Articles