Randomblue
Randomblue

Reputation: 116283

Modifying printf

I would like to modify the function printf to a new function printf2 that simply prepends the message to be printed with Hello.

I could do

void printf2(char message[]) {
    printf("Hello ");
    printf(message);
}

The problem is that I cannot pass the extra arguments for cases when message has %d, %c, etc.

How can I have printf2 accept as many parameters printf can, and pass them on to printf?

Upvotes: 0

Views: 1850

Answers (3)

Dmitry Poroh
Dmitry Poroh

Reputation: 3825

void print_message(char *format, ...)
{
    printf("%s", "Hello: ")
    va_list ptr;
    va_start(ptr, format);
    vprintf(format, ptr);
    va_end(ptr);
}

Note:

  1. printf("%s", "Hello: ") is bit faster than printf("Hello: ") (by skipping scan of the format string phase)
  2. printf(message); is REALLY bad idea. It crash when message has something like "%s".

Upvotes: 0

enyblock
enyblock

Reputation: 1

  1. You should use below function to control the variable parameter.

    void va_start( va_list arg_ptr, prev_param );   
    type va_arg( va_list arg_ptr, type );   
    void va_end( va_list arg_ptr );  
    
  2. Judge the format string. using switch () statement judge %d, %c, %s and so on

Upvotes: 0

Throwback1986
Throwback1986

Reputation: 6005

The comment above points you in the right direction, but here is an example of how to prepend your tag (Hello).

Notes: I have used the s and n version of printf to format a new string that shouldn't overflow my temp buffer, and *MAX_MSG_SIZE* is assumed to be defined appropriately elsewhere.

void printf2(const char *format, ...)
{

    char buffer[MAX_MSG_SIZE] = "";  


    va_list args;


    va_start(args,format);
    vsnprintf(buffer, MAX_MSG_SIZE, format, args);
    va_end(args);   

    printf("Hello: %s\n", buffer);
}

Upvotes: 2

Related Questions