Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,853 questions

51,774 answers

573 users

How to write you own printf() that take different number different types of arguments in C

1 Answer

0 votes
#include <stdio.h>
#include <stdarg.h>
 
void my_printf(const char* fmt, ...) {
    va_list args;
    va_start(args, fmt);
 
    while (*fmt != '\0') {
        if (*fmt == 'd') {
            int i = va_arg(args, int);
            printf(" %4d", i);
        } else if (*fmt == 'c') {
            int ch = va_arg(args, int);
            printf(" %3c", ch);
        } else if (*fmt == 'f') {
            double f = va_arg(args, double);
            printf(" %.6f", f);
        }
        fmt++;
    }
    printf("\n");
 
    va_end(args);
}
 
int main(void)
{
    my_printf("dcf", 100, 'x', 3.14);
    my_printf("cff", 'x', 3.14, 4.872);
}



/*
run:

  100   x 3.140000
   x 3.140000 4.872000

*/

 



answered Apr 7, 2019 by avibootz
...