How to separate format specifiers from characters with printf
Asked Answered
B

2

5

Another way to phrase this question might be "How to end format specifiers in printf"

If I want to print microseconds in this format 100us using the following code...

long microseconds = 100L;
printf("%lus", microseconds);

only prints 100s because the u is combined with the %l and it interprets the format specifier as an unsigned long instead of a long

Bolling answered 4/9, 2022 at 18:44 Comment(5)
%l is not a complete format specification by itself. It might work by accident on some C libraries but it's incorrect to rely on that. Always give complete format specifications (in this case you wanted %ld) and you won't have this problem.Onlybegotten
@Onlybegotten ah, noticed that after posting. The question is more in general, since I'm sure there are other cases where a conflict can occur. I'll try to find a different exampleBolling
The answer for the general case is the same: all conversion specifications must end with one of the "conversion specifier" characters (comprehensive list here: port70.net/~nsz/c/c11/n1570.html#7.21.6.1p8) You will not have a conflict with subsequent text if you make sure always to do that. Also, printf may crash or print nonsense if you don't always do that. I can make that a proper answer later when I'm on a real computer.Onlybegotten
@Onlybegotten I think my confusion came from not realizing that every format specifier has to end with a single conversion specifier symbol/character. And then also mixing up some of the conversion specifiers with other modifiers. Thanks for helping me clear up my confusion!Bolling
Note the L in 100L serves little purpose.Speciosity
M
6

Just write

long microseconds = 100L;
printf("%ldus", microseconds);

Pay attention to that you may not use a length modifier without a conversion specifier.

Monastic answered 4/9, 2022 at 18:55 Comment(1)
....or %lius.Methane
S
1

How to separate format specifiers from characters with printf

If separation is important:

long microseconds = 100L;
printf("%ld" "us", microseconds);

Adjacent literal strings are concatenated. The above is equivalent to "%ldus".

// or maybe via macros
#DEFINE TIME_FMT "%ld"
#DEFINE TIME_SUFFIX "us"
...
printf(TIME_FMT TIME_SUFFIX, microseconds);
Speciosity answered 4/9, 2022 at 21:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.