Use fixed exponent in scientific notation

Format it yourself (see Format Specification Mini-Language): for ix in [.02e9, .2e9, 2e9, 20e9, 200e9, 2000e9]: print(‘{:.3e} => {:0=8.3f}e9’.format(ix, ix / 1e9)) Output 2.000e+07 => 0000.020e9 2.000e+08 => 0000.200e9 2.000e+09 => 0002.000e9 2.000e+10 => 0020.000e9 2.000e+11 => 0200.000e9 2.000e+12 => 2000.000e9 Explanation {:0=8.3f} means “zero-pad, pad between the sign and the number, total field width … Read more

sprintf for unsigned _int64

I don’t know what POSIX has to say about this, but this is nicely handled by core C99: #include <stdio.h> #include <inttypes.h> int main(void) { uint64_t dbFileSize = 99; uint64_t fileSize = 100; char buf[128]; memset(buf, 0x00, 128); sprintf( buf, “\nOD DB File Size = %” PRIu64 ” bytes \t” ” XML file size = … Read more

Using %f to print an integer variable

From the latest C11 draft — §7.16 Variable arguments <stdarg.h>: §7.16.1.1/2 …if type is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined, except for the following cases: — one type is a signed integer type, the other type is the corresponding … Read more

Why scanf(“%d”, […]) does not consume ‘\n’? while scanf(“%c”) does?

It is consistent behavior, you’re just thinking about it wrong. 😉 scanf(“%c”, some_char); // reads a character from the key board. scanf(“%d”, some_int); // reads an integer from the key board. So if I do this: printf(“Insert a character: “); scanf(“%c”, &ch); // if I enter ‘f’. Really I entered ‘f’ + ‘\n’ // scanf … Read more

Correct printf format specifier for size_t: %zu or %Iu?

MS Visual Studio didn’t support %zu printf specifier before VS2013. Starting from VS2013 (e.g. _MSC_VER >= 1800) %zu is available. As an alternative, for previous versions of Visual Studio if you are printing small values (like number of elements from std containers) you can simply cast to an int and use %d: printf(“count: %d\n”, (int)str.size()); … Read more

Why is printf with a single argument (without conversion specifiers) deprecated?

printf(“Hello World!”); is IMHO not vulnerable but consider this: const char *str; … printf(str); If str happens to point to a string containing %s format specifiers, your program will exhibit undefined behaviour (mostly a crash), whereas puts(str) will just display the string as is. Example: printf(“%s”); //undefined behaviour (mostly crash) puts(“%s”); // displays “%s\n”