sscanf() - I/O Function
How is "sscanf()" used in C++?
Explanation
sscanf() is an I/O function that is used to read the data from an array. The return value is equal to the number of variables that is assigned. The value is zero if no fields were assigned, EOF indicates that an error has occurred prior to the first argument.
Syntax:
int sscanf ( const char * str, const char * format, ...);
The following table lists the format specifiers used by the sscanf().
In the above syntax in the format parameter the function discards the whitespace. All the non-whitespace characters except "%" are skipped, then the next character is read. The "%" indicates a format specifier. The following table lists the format specifier used with "sscanf" function.
Type | Description | Argument |
c | Used to read a single character, if the width is more than 1 the function reads all the specified width of characters and stores them in successive locations of the array passed as argument. | char * |
d | Represents a decimal integer that mey be preceeded with +/ - sign. | int * |
e,E,f,g,G | Used to represent a floating point number containing a decimal point that may have a +/- sign with a e or E character. | float * |
o | Specifies an octal value | int * |
s | This format type is used to read string of characters until a whitespace is found. | char * |
u | Unsigned decimal integer | unsigned int * |
x,X | Represents a hexadecimal integer. | int * |
Example :
#include <stdio.h> int main () { char str1 []="Alex has 5 apples"; char str [30]; int i; sscanf (str1,"%s %*s %d",str,&i); printf ("Number of apples %s has is %d\n",str,i); return 0; } |
Result :
Number of apples Alex has is 5
In the above syntax in the format parameter the function discards the whitespace. All the non-whitespace characters except "%" are skipped, then the next character is read. The "%" indicates a format specifier. The following table lists the format specifier used with "sscanf" function.