keywords: C, printf, Format

Format

Example:

/* printf example */
#include <stdio.h>

int main()
{
   printf ("Characters: %c %c \n", 'a', 65);
   printf ("Decimals: %d %ld\n", 1977, 650000L);
   printf ("Preceding with blanks: %10d \n", 1977);
   printf ("Preceding with zeros: %010d \n", 1977);
   printf ("Some different radices: %d %x %o %#x %#o \n", 100, 100, 100, 100, 100);
   printf ("floats: %4.2f %+.0e %E \n", 3.1416, 3.1416, 3.1416);
   printf ("Width trick: %*d \n", 5, 10);
   printf ("%s \n", "A string");
   return 0;
}

Output:

Characters: a A
Decimals: 1977 650000
Preceding with blanks:       1977
Preceding with zeros: 0000001977
Some different radices: 100 64 144 0x64 0144
floats: 3.14 +3e+000 3.141600E+000
Width trick:    10
A string

Reference:
https://www.cplusplus.com/reference/cstdio/printf/

int64 Format

For int64_t type:

#include <inttypes.h>
int64_t t;
printf("%" PRId64 "\n", t);

for uint64_t type:

#include <inttypes.h>
uint64_t t;
printf("%" PRIu64 "\n", t);

you can also use PRIx64 to print in hexadecimal.

Origin: How to portably print a int64_t type in C
https://stackoverflow.com/a/9225648/1645289

Hexadecimal Format
int i = 7;

printf("%#010x\n", i);  // gives 0x00000007
printf("%#08x\n", i);   // gives 0x000007
printf("0x%08x\n", i);  // gives 0x00000007

Also changing the case of x, affects the casing of the outputted characters:

printf("%04x", 4779); // gives 12ab
printf("%04X", 4779); // gives 12AB

Origin: printf() formatting for hexadecimal
https://stackoverflow.com/a/14733875/1645289

C++20 Format
std::format("{:#x}", 42);    // 0x2a
std::format("{:#010x}", 42); // 0x0000002a
printf函数源码实现
#include <stdio.h>  
#include <stdarg.h>  

//va_start(arg,format),初始化参数指针arg,将函数参数format右边第一个参数地址赋值给arg  
//format必须是一个参数的指针,所以,此种类型函数至少要有一个普通的参数,   
//从而提供给va_start ,这样va_start才能找到可变参数在栈上的位置。   
//va_arg(arg,char),获得arg指向参数的值,同时使arg指向下一个参数,char用来指名当前参数型  
//va_end 在有些实现中可能会把arg改成无效值,这里,是把arg指针指向了 NULL,避免出现野指针   

void print(const char *format, ...)
{
    va_list arg;
    va_start(arg, format);

    while (*format)
    {
        char ret = *format;
        if (ret == '%')
        {
            switch (*++format)
            {
            case 'c':
            {
                char ch = va_arg(arg, char);
                putchar(ch);
                break;
            }
            case 's':
            {
                char *pc = va_arg(arg, char *);
                while (*pc)
                {
                    putchar(*pc);
                    pc++;
                }
                break;
            }
            default:
                break;
            }
        }
        else
        {
            putchar(*format);
        }
        format++;  
    }
    va_end(arg);  
}

int main()  
{
    print("%s %s %c%c%c%c%c!\n", "welcome", "to", 'C', 'h', 'i', 'n', 'a');  
    system("pause");  
    return 0;  
}

Origin:
https://blog.csdn.net/iynu17/article/details/51588199


察见渊鱼者不祥,智料隐匿者有殃。----《列子》