void TestPrint(char* format, ...) { va_list argList; va_start(argList, format); printf(format, argList); va_end(argList); } int main() { TestPrint("Test print %s %d\n", "string", 55); return 0; }
I need to get:
Test print string 55
Actually, I get garbage output. What is wrong in this code?
va_list is a complete object type suitable for holding the information needed by the macros va_start, va_copy, va_arg, and va_end. If a va_list instance is created, passed to another function, and used via va_arg in that function, then any subsequent use in the calling function should be preceded by a call to va_end.
The vsprintf is defined in the stdio. h header file. It uses a format string and corresponding arguments to generate a string stored in the provided destination string.
The C library function int vfprintf(FILE *stream, const char *format, va_list arg) sends formatted output to a stream using an argument list passed to it.
Use vprintf()
instead.
Instead of printf
, I recommend you try vprintf
instead, which was created for this specific purpose:
#include <stdio.h> #include <stdlib.h> #include <stdarg.h> void errmsg( const char* format, ... ) { va_list arglist; printf( "Error: " ); va_start( arglist, format ); vprintf( format, arglist ); va_end( arglist ); } int main( void ) { errmsg( "%s %d %s", "Failed", 100, "times" ); return EXIT_SUCCESS; }
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With