liveBook · Manning

Scanf family

As explained in 100 C++ Mistakes and How to Avoid Them

scanf is a C standard-library function that reads formatted input from a stream and converts it according to a format string.

Mistake: treating scanf-family functions as straightforward input tools. They convert values through format specifiers, but a wrong specifier can cause undefined behavior, crashes, or silently incorrect data. The notation can also make ordinary input logic difficult to read and maintain. section 6.1

Several format-string details are easy to misread:

  • Use %lf for a double; %f represents a floating-point value, while d means decimal rather than double. section 6.1
  • Recognize that %i and %d do not necessarily interpret the same input; the sample’s first integer becomes 34 rather than 42. section 6.1
  • Treat complicated format strings as maintenance risks because readers must mentally parse unfamiliar symbols. section 6.1

A safer correction

Replace format-string conversions with typed extraction through std::istringstream, checking str.fail() after each value. The types then communicate the intended conversions directly, and std::string removes the fixed-size character buffer used by the scanf example.

How 100 C++ Mistakes and How to Avoid Them covers it

How deep it goes
Explains specifier mismatches, dense notation, and a stream-based correction without detailing the complete scanf specification.
Examples
Uses a numeric string containing pi, integer values, text, a character suppression, and a fixed-size output buffer.
What you can do after
Diagnose format-specifier mismatches and apply typed stream extraction as an incremental modernization.
How it connects
Links formatted input with format strings, sscanf, printf, typed extraction, and input-failure checks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 C++ Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.