Home  >  Article  >  Backend Development  >  How Can a C Class Handle Variable Arguments with printf/sprintf?

How Can a C Class Handle Variable Arguments with printf/sprintf?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-26 03:34:13156browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn