In C, sscanf() function stands for "String Scan Formatted". This function is used for parsing the formatted strings, unlike scanf() that reads from the input stream, the sscanf() function extracts data from a string. In this article, we will learn how to read data using sscanf() function in C.
Example:
Input:
char *str = "Ram Manager 30";
Output:
Name: Ram
Designation: Manager //parsed string
Age: 30
Read Data Using sscanf Function in C
In C, the sscanf() function can be used to read formatted data from a string rather than a standard input or keyboard. Pass the string to be parsed, a format specifier that defines the expected data types and structure of the input string (like %d, %f, %c, etc), and the list of variables where we want to store the formatted data as a parameter to the sscanf() functions to get the parsed string.
Syntax of sscanf() in C
sscanf(input_str, format, store1, store2, ...);Here,
- input_str is the string from which data needs to be read.
- format tells the type and format of data to be read
- store1, store2, ... represents the variables where the read data will be stored.
C Program to Read Data Using sscanf()
The below program demonstrates how we can read data using sscanf() function in C.
// C program to Read Data Using sscanf()
#include <stdio.h>
#include <string.h>
int main()
{
// Define a string containing the data to be parsed.
char* str = "Ram Manager 30";
// Define variables to hold the parsed data.
char name[10], designation[10];
int age, ret;
// Use sscanf to parse the string into the variables.
ret = sscanf(str, "%s %s %d", name, designation, &age);
// Print the parsed data.
printf("Name: %s\n", name);
printf("Designation: %s\n", designation);
printf("Age: %d\n", age);
return 0;
}
Output
Name: Ram Designation: Manager Age: 30
Time complexity: O(n), where n is the length of the input string.
Auxilliary Space: O(1)
Explanation: In this program, sscanf() reads three items from the string str, so 3 will be assigned to ret. The printf() function is then used to display name, designation, and age.
Note: If the input string does not match the specified format, sscanf() might fail to extract data correctly and may lead to parsing errors.