Home > Backend Development > C++ > 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
Release: 2024-11-26 03:34:13
Original
220 people have browsed it

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, ...);
};
Copy after login

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);
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template