Decoding printf outputs in C (Printf Primer)

I have been working on bringing old code from 1998 to the 21st century. One of the first steps in the process is to convert printf statements to QString variables. No matter how many times I look at printf again, I always forget one or the other. So, for fun, let me decode it together, for the sake of time and in the process, create the first small 'printf primer for Stackoverflow.

In the code, I came across this little gem,

printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g); 

How will the variables a, b, c, d, e, f, g be formatted?

+4
source share
6 answers

Danny is basically right.

a. unsigned decimal, at least 4 characters, space

b. floating point, at least 16 digits before the decimal point (0 is supplemented), 1 digit after the decimal place - s. hexadecimal, minimum 4 characters, 0 padded, letters are printed in upper case
e. as above, but at least 2 characters
e. e is considered int, converted to unsigned char and printed by e. just like e g. This is probably a typo, 4 has no effect. If it is "% .4s", then no more than 4 characters per line will be printed. It is interesting to note that in this case the line should not be terminated by zero.

Edit: jj33 points to 2 errors in b and g above here .

+5
source

@ Jason Day , I think the 4 in the last% 4s are significant if there are less than 4 characters left. If there are more than 4, you are correct,% 4s and% s would be the same, but with less than 4 characters in g% s would remain justified, and% 4s would be correctly justified in the 4 char field.

b actually a minimum of 16 characters for the entire field, including the decimal and numeric digit after the decimal value (16 common characters versus 18 common characters)

+5
source

Here is my printf primer: http://www.pixelbeat.org/programming/gcc/format_specs.html

I always compile using -Wall with gcc, which will warn about any inconsistencies between the supplied printf formats and variables.

+4
source

@ jj33, you are absolutely right on both points.

 #include <stdio.h> int main(int argc, char *argv[]) { char *s = "Hello, World"; char *s2 = "he"; printf("4s: '%4s'\n", s); printf(".4s: '%.4s'\n", s); printf("4s2: '%4s'\n", s2); printf(".4s2: '%.4s'\n", s2); return 0; } $ gcc -o foo foo.c $ ./foo 4s: 'Hello, World' .4s: 'Hell' 4s2: ' he' .4s2: 'he' 

Good booty!

+3
source

a. decimal, four significant digits

b. Not sure

with. hex, minimum 4 characters

e. Also hex, minimum 2 characters

e. 1 character

f. Character string, minimum 4

0
source

What you really need is a tool that takes format strings in printf () statements and converts them to equivalent QString-based function calls.
Does anyone want to spend their free software time developing such a tool?

Placeholder for a URL for free hosting of software containing the source code of such a tool

0
source

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


All Articles