I did not understand the purpose of width in "%[-][width].[precision]conversion character " (used in printf statements) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

I did not understand the purpose of width in "%[-][width].[precision]conversion character " (used in printf statements)

Can anyone explain me with an example

7th Oct 2019, 2:47 PM
Sk. Ahmed Razha Khan
Sk. Ahmed Razha Khan - avatar
2 Answers
+ 3
From wikipedia https://en.m.wikipedia.org/wiki/Printf_format_string: "The Width field specifies a minimum number of characters to output, and is typically used to pad fixed-width fields in tabulated output, where the fields would otherwise be smaller, although it does not cause truncation of oversized fields." Examples: // Width is 2 and zero flag is set // meaning that padding is replaced with zeroes // instead of spaces printf("%02d:%02d", 2, 30); // 02:30 // Row column thing with spaced padding printf( "%10s%10s\n" "%10s%10d\n" "%10s%10d\n" "%10s%10d\n", "Name", "Age", "Bob", 7, "Juliet", 9, "SomeNameLongerThan10Characters", -1 ); // Let's say we wanted to print the float 3.14159 // as 003.142 for absolutely no reason // precision would be 3 (digits after decimal) // width would be the width of the entire thing // including the decimal point and the digits after // width = digitsBeforeDecimalPoint + 1 + precision // width = 3 + 1 + 3 = 7 printf("%07.3f", 3.14159f);
7th Oct 2019, 3:35 PM
jtrh
jtrh - avatar