scanf - C stdio.h

C examples for stdio.h:scanf

Type

function

From


<cstdio>
<stdio.h>

Description

Read formatted data from stdin

Prototype

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
specifierDescription<th>Characters extracted</th>
i, uIntegerdigits, 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).
dDecimal integerdecimal digits (0-9), optionally preceded by a sign (+ or -).
oOctal integeroctal digits (0-7), optionally preceded by a sign (+ or -).
xHexadecimal integerhexadecimal digits (0-9, a-f, A-F), optionally preceded by 0x or 0X, and all optionally preceded by a sign (+ or -).
f, e, gFloating point numberdecimal 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.
cCharacterThe next character.
sString of charactersAny number of non-whitespace characters, stopping at the first whitespace character found.
pPointer addressA sequence of characters representing a pointer.
[characters]Scansetonly read the characters specified between the brackets.
[^characters]Negated scansetnot read the characters specified between the brackets.
nCountNo input is consumed. The number of characters read so far is saved in the signed int.
%%A % followed by another % matches a single %.
sub-specifierdescription
*asterisk indicates that the data is to be read from the stream but ignored.
widthset the maximum number of characters to be read.
lengthOne of hh, h, l, ll, j, z, t, L (optional).

Return Value

On success, the function returns the number of items filled.

Example

This example demonstrates some of the types that can be read with scanf:

Demo Code


#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;
}

Related Tutorials