C examples for stdio.h:scanf
function
<cstdio> <stdio.h>
Read formatted data from stdin
int scanf ( const char * format, ... );
format string can have the following value.
Whitespace character
scanf 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, the function returns the number of items filled.
This example demonstrates some of the types that can be read with scanf:
#include <stdio.h> int main ()/*from w w w . jav a 2 s. co m*/ { char str [80]; int i; printf ("Enter your family name: "); scanf ("%79s",str); printf ("Enter your age: "); scanf ("%d",&i); printf ("Mr. %s , %d years old.\n",str,i); printf ("Enter a hexadecimal number: "); scanf ("%x",&i); printf ("You have entered %#x (%d).\n",i,i); return 0; }