Reputation: 116283
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
Reputation: 3825
void print_message(char *format, ...)
{
printf("%s", "Hello: ")
va_list ptr;
va_start(ptr, format);
vprintf(format, ptr);
va_end(ptr);
}
Note:
Upvotes: 0
Reputation: 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 );
Judge the format string. using switch () statement judge %d
, %c
, %s
and so on
Upvotes: 0
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