ALERT

[WEBINAR] Fast Analytics for Big Data and Small

Scanf

Definition - What does Scanf mean?

In the C programming language, scanf is a function that reads formatted data from stdin (i.e, the standard input stream, which is usually the keyboard, unless redirected) and then writes the results into the arguments given.

This function belongs to a family of functions that have the same functionality but differ only in their source of data. For example, fscanf gets its input from a file stream, whereas sscanf gets its input from a string.

Techopedia explains Scanf

The scanf function has the following prototype/signature:

int scanf( const char *format, ... );

where

  • int (integer) is the return type
  • format is a string that contains the type specifier(s) (see below)
  • "..." (ellipsis) indicates that the function accepts a variable number of arguments; each argument must be a memory address where the converted result is written to

A simple type specifier consists of a percent (%) symbol and an alpha character that indicates the type. Below are a few examples of the type specifiers recognized by scanf:

  • %c — Character
  • %d — Signed integer
  • %x — Unsigned integer in hexadecimal format
  • %f — Floating point
  • %s — String

The function works by reading input from the standard input stream and then scans the contents of "format" for any format specifiers, trying to match the two. On success, the function writes the result into the argument(s) passed.

For example, if the function call is

scanf( "%c%d", &var1, &var2 );

and the user types "a1", the function will write "a" into "var1" and "1" into "var2". If the function call, however, is

scanf( "%x", &var );

the same input will be read as the hexadecimal number "a1," which is 161 in decimal.

The function returns the following value:

  • >0 — The number of items converted and assigned successfully.
  • 0 — No item was assigned.
  • <0 — Read error encountered or end-of-file (EOF) reached before any assignment was made.
Share this: