ArticleslgStudy

science

Scanf

Scanf is a science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Scanf rather than just read about it. In short: scanf, short for scan formatted, is a C standard library function that reads and parses text from standard input. The function accepts a format string parameter that specifies the layout of input text.

Key takeaways

  • Scanf belongs to science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Scanf to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Scanf from memory before moving on to harder problems.

Reference excerpt

scanf, short for scan formatted, is a C standard library function that reads and parses text from standard input. The function accepts a format string parameter that specifies the layout of input text. The function parses input text and loads values into variables based on data type. The format string is almost identical to the form used by the printf, which provides formatted output (templating). scanf and printf are practically inverse functions of each other. There are companion functions that read from a file (fscanf) or an existing string (sscanf). Similar functions, with other names, predate C, such as readf in ALGOL 68.

History Mike Lesk's portable input/output library, including scanf, officially became part of Unix in Version 7. This would be inherited into ANSI C89, the first C standard. For reading input, C++ typically uses std::cin, while Java uses a class java.util.Scanner. A modernization of ::printf() was introduced to C++, based on fmtlib, which added std::format() (in C++20) and std::print() and std::println() (in C++23). However, no analogous ::scanf() modernization has been introduced, though one has been proposed based on scnlib.

Usage The scanf function reads input for numbers and other datatypes from standard input. The following C code reads a variable number of unformatted decimal integers from standard input and prints each of them out on separate lines:

For input:

456 123 789 456 12 456 1 2378

The output is:

To print out a word:

No matter what the data type the programmer wants the program to read, the arguments (such as &n above) must be pointers pointing to memory. Otherwise, the function will not perform correctly because it will be attempting to overwrite the wrong sections of memory, rather than pointing to the memory location of the variable you are attempting to get input for. In the last example an address-of operator (&) is not used for the argument: as word is the name of an array of char, as such it is (in all contexts in which it evaluates to an address) equivalent to a pointer to the first element of the array. While the expression &word would numerically evaluate to the same value, semantically, it has an entirely different meaning in that it stands for the address of the whole array rather than an element of it. This fact needs to be kept in mind when assigning scanf output to strings. As scanf is designated to read only from standard input, many programming languages with interfaces, such as PHP, have derivatives such as sscanf and fscanf but not scanf itself.

Format string specifications The formatting placeholders in scanf are more or less the same as that in printf, its reverse function. As in printf, the POSIX extension n$ is defined. There are rarely constants (i.e., characters that are not formatting placeholders) in a format string, mainly because a program is usually not designed to read known data, although scanf does accept these if explicitly specified. The exception is one or more whitespace characters, which discards all whitespace characters in the input. Some of the most commonly used placeholders follow:

%a : Scan a floating-point number in its hexadecimal notation. %d : Scan an integer as a signed decimal number. %i : Scan an integer as a signed number. Similar to %d, but interprets the number as hexadecimal when preceded by 0x and octal when preceded by 0. For example, the string 031 would be read as 31 using %d, and 25 using %i. The flag h in %hi indicates conversion to a short and hh conversion to a char. %u : Scan for decimal unsigned int (Note that in the C99 standard the input value minus sign is optional, so if a minus sign is read, no errors will arise and the result will be the two's complement of a negative number, likely a very large value. See strtoul().) Correspondingly, %hu scans for an unsigned short and %hhu for an unsigned char. %f : Scan a floating-point number in normal (fixed-point) notation. %g, %G : Scan a floating-point number in either normal or exponential notation. %g uses lower-case letters and %G uses upper-case. %x, %X : Scan an integer as an unsigned hexadecimal number. %o : Scan an integer as an octal number. %s : Scan a character string. The scan terminates at whitespace. A null character is stored at the end of the string, which means that the buffer supplied must be at least one character longer than the specified input length. %c : Scan a character (char). No null character is added. whitespace: Any whitespace characters trigger a scan for zero or more whitespace characters. The number and type of whitespace characters do not need to match in either direction. %lf : Scan as a double floating-point number. "Float" format with the "long" specifier. %Lf : Scan as a long double floating-point number. "Float" format the "long long" specifier. %n : Nothing is expected. The number of characters consumed thus far from the input is stored through the next pointer, which must be a pointer to int. This is not a conversion and does not increase the count returned by the function. The above can be used in compound with numeric modifiers and the l, L modifiers which stand for "long" and "long long" in between the percent symbol and the letter. There can also be numeric values between the percent symbol and the letters, preceding the long modifiers if any, that specifies the number of characters to be scanned. An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable. No argument behind the format string should be included for this dropped variable. The ff modifier in printf is not present in scanf, causing differences between modes of input and output. The ll and hh modifiers are not present in the C90 standard, but are present in the C99 standard. An example of a format string is

… excerpt ends here. Continue reading the full article.

Worked examples

Example 1 — a first encounter with Scanf

Start with the simplest possible case. Write down what Scanf claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Scanf before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Scanf ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Scanf

In research
Scanf appears in science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Scanf in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Scanf is common in secondary-school and first-year university syllabi. It links to neighbouring topics C standard library, so understanding it makes those chapters shorter.
In everyday life
Look for Scanf outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Scanf” →

How to study Scanf in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Scanf means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Scanf out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Scanf in simple terms?

scanf, short for scan formatted, is a C standard library function that reads and parses text from standard input. The function accepts a format string parameter that specifies the layout of input text.

Why does Scanf matter?

Because it connects several science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Scanf?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Scanf.

Tags

  • C standard library

Keep exploring