What is vscanf in C?
The vscanf function requires both the stdio.h and stdarg.h header files to work. It is used to read data from the stdin and store it in different elements of a variable argument list according to the specified format.
Syntax
The following is the syntax to declare the vscanf function:
Parameters
The vscanf_s function takes in 2 mandatory arguments:
-
format: The pointer to the format string that may include format specifiers like%s. -
arglist: A variable list of arguments of typeva_list. This data type is defined in thestdarg.hheader file.
An object of type
va_listneeds to be initialized by theva_startmacro and needs to be released after use through theva_endmacro
Return value
vscanf 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.
Example
The following is an example where we take a value as input followed by its unit and display it on stdout differently. For this example, we constructed a different function, get_store, that handles initializing and storage of the arglist. An example of the required input would be “500 Meters”:
NOTE: To use standard input for the following code, type your input into the text box below the code widget and click run.
#include <stdio.h>#include <stdarg.h>// function to automatically initialize the list of argumentsvoid get_store ( 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 vscanfvscanf (format, arglist);// releasing the arglish variable using the va_end macrova_end (arglist);}int main (){// variables to store data intoint magnitude;char unit[40];// 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 (" %d %s ", &magnitude, unit);//printing out the variables to check data in itprintf ("magnitude: %d\nunit: %s\n", magnitude, unit);return 0;}
Enter the input below
Free Resources