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. vsprintf
is different from the normal sprintf
because, instead of directly taking in arguments corresponding to the format string, it takes in a single variable list of arguments as input.
The following is the syntax to declare the vsprintf
function:
The sprintf_s
function takes in 3 arguments:
s
: The pointer to the destination string where the formatted string will be stored
format
: The pointer to the format string. This may include format specifiers like %s
.
arglist
: A variable list of arguments of type va_list
. This data type is defined in the stdarg.h
header file.
An object of type
va_list
needs to be initialized by theva_start
macro and needs to be released after use through theva_end
macro
vsprintf
can return one of the two things:
Upon successful execution, it returns the number of items filled in the list of variable arguments given in the parameters.
If there is a failure during the assignment of arguments or while interpreting an input, or EOF
(End Of File) is returned.
The following is an example where we take two variables, one with the magnitude of the measurement and the other containing the units. For this example, we constructed a different function, get_store
, that handles initializing and storage of the arglist
. It also runs the vsprintf
function to store the created string into the provided character array:
#include <stdio.h>#include <stdarg.h>// function to automatically initialize the list of argumentsvoid get_store ( char* dest_str, const char * format, ... ){// the arglist holds list of all arguments fed to this functionva_list arglist;// initializing the arglish using the vs_start macrova_start (arglist, format);// putting the arguments into the arglist using vsprintfvsprintf (dest_str, format, arglist);// releasing the arglish variable using the va_end macrova_end (arglist);}int main (){// variable to store the final string intochar dest[40];// variables whose data we use to form the final stringint magnitude = 500;char unit[40] = "meters";// sending format string and arguments to the get_store function// this format string requires an input with first an integer folllowed by a stringget_store (dest, "The quantity is %d %s ", magnitude, unit);//printing out the variables to check data in itprintf ("%s\n", dest);return 0;}
Free Resources