C++: how to get fprintf results as a std::string w/o sprintf

Here’s the idiom I like for making functionality identical to ‘sprintf’, but returning a std::string, and immune to buffer overflow problems. This code is part of an open source project that I’m writing (BSD license), so everybody feel free to use this as you wish. #include <string> #include <cstdarg> #include <vector> #include <string> std::string format … Read more

colorful text using printf in C

I know that this is incredibly easy to do in C++, but I found this for you to look at in C: #include <stdio.h> #include <windows.h> // WinApi header int main() { HANDLE hConsole; int k; hConsole = GetStdHandle(STD_OUTPUT_HANDLE); // you can loop k higher to see more color choices for(k = 1; k < … Read more

‘%d’ expects argument of type ‘int’, but argument 2 has type ‘long unsigned int’ [-Wformat=] [duplicate]

sizeof returns size_t you need to use %zu for the format string instead of %d. The type of unsigned integer of size_t can vary (depending on platform) and may not be long unsigned int everywhere, which is covered in the draft C99 standard section 6.5.3.4 The sizeof operator paragraph 4: The value of the result … Read more

cross-platform printing of 64-bit integers with printf

There are a couple of approaches. You could write your code in C99-conforming fashion, and then supply system-specific hacks when the compiler-writers let you down. (Sadly, that’s rather common in C99.) #include <stdint.h> #include <inttypes.h> printf(“My value is %10” PRId64 “\n”, some_64_bit_expression); If one of your target systems has neglected to implement <inttypes.h> or has … Read more

Printf long long int in C with GCC?

If you are on windows and using mingw, gcc uses the win32 runtime, where printf needs %I64d for a 64 bit integer. (and %I64u for an unsinged 64 bit integer) For most other platforms you’d use %lld for printing a long long. (and %llu if it’s unsigned). This is standarized in C99. gcc doesn’t come … Read more

Using colors with printf

Rather than using archaic terminal codes, may I suggest the following alternative. Not only does it provide more readable code, but it also allows you to keep the color information separate from the format specifiers just as you originally intended. blue=$(tput setaf 4) normal=$(tput sgr0) printf “%40s\n” “${blue}This text is blue${normal}” See my answer HERE … Read more

Why use sprintf function in PHP?

sprintf has all the formatting capabilities of the original printf which means you can do much more than just inserting variable values in strings. For instance, specify number format (hex, decimal, octal), number of decimals, padding and more. Google for printf and you’ll find plenty of examples. The wikipedia article on printf should get you … Read more