Prints formatted text to a string using a variable length argument list.
Include
<stdio.h>
<stdarg.h>
Prototype
int vsprintf(char *s, const char *format, va_list ap);
Arguments
s |
storage string for output |
format
|
format control string |
ap
|
pointer to a list of arguments |
Return Value
Returns number of characters stored in s excluding the terminating null character.
Remarks
The format argument has the same syntax and use that it has in
printf.
To access the variable length argument list, the ap variable
must be initialized by the macro va_start and may be reinitialized by
additional calls to va_arg. This must be done before the
vsprintf function is called. Invoke va_end after the
function returns. For more details, see stdarg.h.
This function requires a heap.
Example
#include <stdio.h> /* for vsprintf, printf */
#include <stdarg.h> /* for va_start, */
/* va_list, va_end */
void errmsg(const char *fmt, ...)
{
va_list ap;
char buf[100];
va_start(ap, fmt);
vsprintf(buf, fmt, ap);
va_end(ap);
printf("Error: %s", buf);
}
int main(void)
{
int num = 3;
errmsg("The letter '%c' is not %s\n", 'a',
"an integer value.");
errmsg("Requires %d%s\n", num,
" or more characters.\n");
}
Example Output
Error: The letter 'a' is not an integer value.
Error: Requires 3 or more characters.