How to pass variable number of arguments to printf/sprintf

c++, printf, variadic-functions

Solution

Use `vfprintf`, like so:

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

This outputs the results to `stderr`. If you want to save the output in a string instead of displaying it use `vsnprintf`. (Avoid using `vsprintf`: it is susceptible to buffer overflows as it doesn't know the size of the output buffer.)

Problem

I have a class that holds an "error" function that will format some text. I want to accept a variable number of arguments and then format them using `printf`. Example: ``` class MyClass { public: void Error(const char* format, ...); }; ``` The `Error` method should take in the parameters, call `printf`/`sprintf` to format it and then do something with it. I don't want to write all the formatting myself so it makes sense to try and figure out how to use the existing formatting.

Original source

Related problems