C examples for stdio.h:sscanf
function
<cstdio> <stdio.h>
Read formatted data from string
int sscanf ( const char * s, const char * format, ...);
Parameter | Description |
---|---|
s | source C string. |
format | a format string |
format string can have the following value.
Whitespace character
sscanf will read and ignore any whitespace characters encountered before the next non-whitespace character.
A single whitespace in the format string marks any quantity of whitespace characters extracted from the stream.
Non-whitespace character, except format specifier (%) is discarded and the function continues.
Format specifiers have the following prototype:
%[*][width][length]specifier Where the
specifier | Description | <th>Characters extracted</th> |
---|---|---|
i, u | Integer | digits, optionally preceded by a sign (+ or -). Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and 0x hexadecimal digits (0-f). |
d | Decimal integer | decimal digits (0-9), optionally preceded by a sign (+ or -). |
o | Octal integer | octal digits (0-7), optionally preceded by a sign (+ or -). |
x | Hexadecimal integer | hexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -). |
f, e, g | Floating point number | decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer. |
c | Character | The next character. |
s | String of characters | Any number of non-whitespace characters, stopping at the first whitespace character found. |
p | Pointer address | A sequence of characters representing a pointer. |
[characters] | Scanset | only read the characters specified between the brackets. |
[^characters] | Negated scanset | not read the characters specified between the brackets. |
n | Count | No input is consumed. The number of characters read so far is saved in the signed int. |
% | % | A % followed by another % matches a single %. |
sub-specifier | description |
---|---|
* | asterisk indicates that the data is to be read from the stream but ignored. |
width | set the maximum number of characters to be read. |
length | One of hh, h, l, ll, j, z, t, L (optional). |
On success, returns the number argument filled.
#include <stdio.h> int main ()/*from w w w . ja va 2 s .c o m*/ { char sentence []="this is a test 1234"; char str [20]; int i; sscanf (sentence,"%s %*s %d",str,&i); printf ("%s -> %d\n",str,i); return 0; }