Home >Backend Development >C++ >How to Pass a Variable Number of Arguments to printf/sprintf in C and C ?
In C and C , the printf and sprintf functions are used for formatted printing and writing. These functions allow for the specification of a format string that controls how subsequent arguments are printed. However, there may be instances where the number of arguments to be printed is not known in advance. This raises the question of how to pass a variable number of arguments to these functions.
The standard C library provides the vfprintf function, which can handle a variable number of arguments. It takes two mandatory arguments:
The following code snippet demonstrates how to use vfprintf:
void Error(const char* format, ...) { va_list argptr; va_start(argptr, format); vfprintf(stderr, format, argptr); va_end(argptr); }
In this example, the Error function takes a format string as the first argument and an arbitrary number of additional arguments. These arguments are accessed through the va_list, which is initialized using va_start. The vfprintf function is then called with the format string and the va_list. Finally, va_end is used to clean up the va_list.
The above is the detailed content of How to Pass a Variable Number of Arguments to printf/sprintf in C and C ?. For more information, please follow other related articles on the PHP Chinese website!