The sscanf() function in C

sscanf() function allows us to read formatted data from a string rather than standard input or keyboard. Its syntax is as follows:

Syntax: int sscanf(const char *str, const char * control_string [ arg_1, arg_2, ... ]);

The first argument is a pointer to the string from where we want to read the data. The rest of the arguments of sscanf() is same as that of scanf(). It returns the number of items read from the string and -1 if an error is encountered.

The following program demonstrates how sscanf() works:

#include<stdio.h>
#include<string.h>

int main()
{
    char *str = "Tom Manager 28";
    char name[10], designation[10];
    int age, ret;

    ret = sscanf(str, "%s %s %d", name, designation, &age);

    printf("Name: %s\n", name);
    printf("Designation: %s\n", designation);
    printf("Age: %d\n", age);

    // signal to operating system program ran fine
    return 0;
}

Expected Output:

Name: Tom
Designation: Manager
Age: 28

How it works

In line 6, we have declared and initialized a variable str of type pointer to char.

In line 7, we have declared two arrays of character name and designation of size 10 characters.

In line 8, we have declared variable age of type int.

In line 10, sscanf() function is called to read the data from the string pointed to by str. Notice that the string literal "Tom Manager 28"  contains three pieces of information name, designation and age separated by space. To read all the three items we need to supply three variables of appropriate type to the scanf() function. Then variable ret  is assigned the number of items read by sscanf() function. In this case, we are reading three items from the string str, so 3 will be assigned to ret.

We are not obliged to read all the items in the string literal, if we want we can also read one or two items from it.

ret = sscanf(str, "%s %s", name, designation);

Here we are only reading and name and designation that's why only two variables are provided to sscanf().

At last printf() statements is used to display name, designation, age and ret.