How to pass variable number of arguments to printf/sprintf

user5722 picture user5722 · Jun 29, 2009 · Viewed 117.1k times · Source

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.

Answer

John Kugelman picture John Kugelman · Jun 29, 2009
void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.