Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c
string

What is vsscanf_s() in C?

Kainat Asif

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

vsscanf_s() reads a character string and writes the content of the string into a list of pointed addresses in the specified format. This method validates the arguments at runtime before writing them.

Declaration

The declaration of vsscanf_s() is as follows:

int vsscanf_s (const char* buffer, const char* format, va_list args);

Note: The vsscanf_s() function is not supported by some compilers. If a compiler supports vsscanf_s(), the value of STDC_WANT_LIB_EXT1 is set to 1.

Parameters

  • buffer: Pointer to the character string from which we read the input.
  • format: Format specifiers of the input to be read.
  • args: Pointer to the list of arguments in which data will be stored.

Return value

If the read operation from the input stream is successful, vsscanf_s() returns the number of arguments that are read. If the read operation is not successful, EOFEnd-of-File is returned.

Example

The code below demonstrates the use of vsscanf_s():

#include <stdio.h>
#include <stdarg.h>
int readFormatted(const char * str, const char * fmt, ...)
{
int len = 0;
va_list args;
va_start(args, fmt);
len = vsscanf_s(str, fmt, args);
va_end(args);
return len;
}
int main ()
{
char buffer[20];
int x;
int y;
float a;
readFormatted("5 times 6", " %d %s %d ", &x, buffer, &y);
printf ("%d %s %d equals %d", x, buffer, y, x*y);
return 0;
}

Output

5 times 6 equals 30

Explanation

The code in line 21 formats the character string based on the parameters following the string and then prints it in line 22.

Note: The function above is not supported by the GCC compiler, hence you will get an implicit declaration of the function vsscanf_s() in error. Use the following variant to get the job done: int vsscanf (const char* buffer, const char* format, va_list args);.

RELATED TAGS

c
string

CONTRIBUTOR

Kainat Asif
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring