Scanf

Why Trust Techopedia

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.

Advertisements

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.
Advertisements

Related Terms

Margaret Rouse
Technology expert
Margaret Rouse
Technology expert

Margaret is an award-winning writer and educator known for her ability to explain complex technical topics to a non-technical business audience. Over the past twenty years, her IT definitions have been published by Que in an encyclopedia of technology terms and cited in articles in the New York Times, Time Magazine, USA Today, ZDNet, PC Magazine, and Discovery Magazine. She joined Techopedia in 2011. Margaret’s idea of ​​a fun day is to help IT and business professionals to learn to speak each other’s highly specialized languages.