C stdio sscanf() Function
Example
Extract a number from a string:
char number[] = "24 hours";
int num;
sscanf(number, "%d", num);
printf("%d", num);
Definition and Usage
The sscanf()
function reads data from a char
array and writes it into memory locations specified by the arguments.
The sscanf()
function is defined in the <stdio.h>
header file.
The format parameter is a string that describes the format of the data that is expected from the file. If the content of the array does not match the format then the function stops reading at the point where the first mismatch occurs.
The format string can contain format specifiers which specify which parts of the data should be written to the arguments. Each format specifier corresponds to one of the additional arguments of the function. Details about format specifiers can be found on the scanf() reference page.
Syntax
sscanf(char * source, const char * format, arg1, arg2...);
Parameter Values
Parameter | Description |
---|---|
source |
Required. A char array used as the data source.
|
format | Required. A string representing the format of the data expected from the array. |
arg1, arg2... | Optional. Any number of additional arguments which are pointers to memory where values can be written. |
Technical Details
Returns: | An int value representing the number of arguments that were written to. It returns the constant EOF if an error occurred. |
---|
More Examples
Example
Extract numbers the sequence "1 + 2 = 3":
int a, b, c;
char source[] = "1 + 2 = 3";
sscanf(source, "%i + %i = %i", &a, &b, &c);
printf("a = %d \n", a);
printf("b = %d \n", b);
printf("c = %d \n", c);
Example
Read a hexadecimal number and output its value in decimal:
int num;
char hex[] = "FFAD01";
sscanf(hex, "%x", &num);
printf("%d", num);
Example
Search for either "x", "y" or "z" in the user input:
char c;
char source[] = "yes";
int found = sscanf(source, "%[xyz]", &c);
if(found > 0) {
printf("Found %c", c);
} else {
printf("Character not found");
}