Home > Article > Backend Development > How Can a C Class Handle Variable Arguments with printf/sprintf?
Passing Variable Arguments to printf/sprintf
Question:
How can a class define a method that accepts a variable number of arguments and formats them using printf?
Example:
Consider a class with an "error" method:
class MyClass { public: void Error(const char* format, ...); };
The Error method should retrieve the variable arguments, format them using printf/sprintf, and perform some action.
Answer:
To accomplish this, use vfprintf:
void Error(const char* format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); }
This outputs the formatted text to stderr. To save the output to a string, use vsnprintf instead. Avoid using vsprintf, as it can cause buffer overflows.
The above is the detailed content of How Can a C Class Handle Variable Arguments with printf/sprintf?. For more information, please follow other related articles on the PHP Chinese website!