In C, sscanf()
is used to read formatted data. It works much like scanf() but the data will be read from a string instead of the console.
In order to read formatted data from a string, first, we must know the syntax of the function, which is shown below.
#include<stdio.h>int main() {int sscanf(const char *read, const char *format,. . .,storage_variables )}
Now let’s look at what parameters does this function take and what it returns.
read
: This is the pointer to the string that is to be read.
storage_variables
Additional argument(s) that the function can take in order to store the value that is being read from the pointer. Here, if the value is being stored in a regular variable and not a pointer then the variable name must be preceded by the & sign.
format
: These are the format specifiers according to which the data will be read from the input string.
A format specifier is a unique set of characters which is used to format the data being read in a certain way. It is preceded by a % sign and then the relevant symbol. The symbols are as follows:
Symbol | Type |
---|---|
s | string |
c | single character |
d | decimal integer |
e, E, f, g, G | floating points |
u | unsigned integer |
x, X | hexadecimal number |
int
value which represents the total number of items read.EOF
error is returned.Now that we know about the syntax, let’s look at a few examples to better understand sscanf()
.
The first example shows you how to read just a single data type in an input string.
#include<stdio.h>int main() {char* buffer = "Hello";char store_value[10];int total_read;total_read = sscanf(buffer, "%s" , store_value);printf("Value in buffer: %s",store_value);printf("\nTotal items read: %d",total_read);return 0;}
The example below shows how to read a space separated two words long string into two separate variables.
#include<stdio.h>int main() {char* buffer = "Hello World";char store_hello[10], store_world[10];int total_read;total_read = sscanf(buffer, "%s %s" , store_hello, store_world);printf("Value in first variable: %s",store_hello);printf("\nValue in second variable: %s",store_world);printf("\nTotal items read: %d",total_read);return 0;}
The example below shows how to read a string and an integer from the same buffer
value.
#include<stdio.h>int main() {char* buffer = "Hello 20";char store_string[10];int store_integer;int total_read;total_read = sscanf(buffer, "%s %d" , store_string, &store_integer);printf("String value in buffer: %s" ,store_string);printf(" \nInteger value in buffer: %d",store_integer);printf("\nTotal items read: %d",total_read);return 0;}