Programming Fundamentals Using C++

L04 · Console I/O with `cin`/`cout`: Streams, Formatting, and Input Validation Basics

Module 2 — Variables, Data Types, and Input/Output · Week 2 · Lecture 4 of 32 · 120 minutes Outcomes: CLO-2 · PF-2.3, PF-2.4 · LEARNING_OUTCOMES.md · Lab 1 week

Learning objectives

  1. Read values of any built-in type with std::cin (chained and single) and write formatted output with std::cout plus fixed, setprecision, setw manipulators from <iomanip> (PF-2.3).
  2. Predict the stream-state consequences of typing the wrong kind of input, and write a program that detects and recovers from a failed read (PF-2.4).
  3. Explain why cin >> x skips leading whitespace but >> stops at it (PF-2.3).

Prerequisites

L03 (can declare/initialize typed variables; assignment semantics).

Concept sequence

  1. Streams as faucets: cout out, cin in
  2. Reading into variables: >> chains, whitespace behavior
  3. Output formatting: fixed, setprecision, setw
  4. When input goes wrong: stream state fail()
  5. Recovery: clear() + ignore(), re-prompt loop preview
  6. Prompt-echo discipline (always echo what you read)

Teaching topics (detailed)

C++ examples required

FileRole
io_age_check.cpp ✅prompt/read/echo/validate age; fail-state recovery demonstrated live
(live) format_table.cpp3-column formatted table with setw (grades sheet)

Conceptual explanation (beginner-first)

So far every value lived inside the program text. Real programs converse: they ask (output), the user answers (input), and the program reacts. C++ models both directions as streams — imagine faucets: cout is the faucet pouring text onto the screen; cin is the drain collecting what the user types.

cin >> age reads one whitespace-separated token and converts it into a number stored in age. Two consequences surprise beginners: the read stops at the first space (one >> never grabs a full line), and if the user types something that cannot be a number, the stream itself fails — and stays failed until you repair it. That failure is not a crash; it is a flag, and flags can be checked and cleared. That is exactly what "input validation" means in this course: read, check the flag, repair or re-prompt.

Formatting is the reverse courtesy: fixed and setprecision(2) make money look like money (19.9 → 19.90) without touching the stored value — only its display changes.

Terminology and definitions

TermDefinition
StreamA channel data flows through (cin in, cout/cerr out)
TokenA whitespace-separated chunk of input (>> reads one)
Stream stateThe flags describing the last operation: good / failed
fail()True when the last read could not produce the requested type
clear()Reset the state flags (does NOT discard buffered text)
ignore(n, '\n')Discard up to n chars, stopping after a newline (buffer repair)
ManipulatorA stream modifier like fixed, setprecision, setw
<iomanip>Header providing setprecision, setw
EchoRe-print what was read, so user and program agree on what happened
PromptText printed before a read, telling the user what to type

Syntax and C++ examples

#include <iostream>
#include <iomanip>     // setprecision, setw

int age{};
std::cout << "Age: ";          // prompt (no newline)
std::cin >> age;               // read one token into age

if (!(std::cin >> value))      // the validation check pattern
{
    std::cin.clear();          // 1) reset flags
    std::cin.ignore(1000, '\n');  // 2) flush the bad line
}

std::cout << std::fixed << std::setprecision(2) << 19.9 << '\n';  // 19.90
std::cout << std::setw(6) << 42 << "|" << '\n';                    // "    42|"
PieceMeaning
cin >> x;Read one token, convert to x's type, store
cin >> a >> b;Chained reads (whitespace, incl. newlines, is skipped)
if (!(std::cin >> x))The validation test: did the read succeed?
clear() + ignore(...)The repair PAIR — clear flags, then flush the line
fixed + setprecision(2)Always-2-decimals display (money)
setw(6)Next item printed right-aligned in a 6-wide field

Line-by-line code explanation

examples/io_age_check.cpp:

  1. #include <limits> — needed for the large count used in the professional ignore call.
  2. int age{0}; — initialized before any read (never read a dirty box).
  3. if (!(std::cin >> age)) — attempt the read; negate the stream's truth: a failed stream is "false", so ! makes failure enter the if.
  4. std::cin.clear(); — reset the fail flag. Without this, every later read instantly fails regardless of input.
  5. std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); — discard up to "a huge number" of characters, stopping after the newline — i.e., throw away the whole bad line. Doing clear() without ignore() leaves abc in the buffer; the next read fails again.
  6. std::cout << "Registered age: " << age << '\n'; — the echo: the user sees what the program understood (here, the default 0).
  7. The if (age >= 18) ... else ... — a first taste of decisions, fully

developed in Module 4.

Output prediction questions (with answers)

  1. cin >> a >> b; with input 12 34 on one line — ? — a=12, b=34 (whitespace, including that line break, is skipped between reads).
  2. Same statement, input 12 34 56 — what is left unread? — 56 (nothing here consumes it — where it matters arrives in Module 11).
  3. User types abc for an int — value of the variable? — Unspecified (often
  4. AND the stream is now failed; both facts matter.
  5. cout << fixed << setprecision(1) << 2.25; — ? — 2.3 (bankers would quibble; the display rounds, the stored value does not).
  6. cout << setw(5) << 42 << "|"; — ? — 42| (right-aligned in 5; the | shows the padding).

Common errors and debugging examples

ErrorSymptomFix
Expecting >> to read a full line"Data Science" read as just "Data"getline for lines (Module 11); >> reads tokens
clear() without ignore()Next read fails again — "validation loop" spinsAlways repair with the PAIR
ignore() without clear()Stream still failed; input discarded for nothingSame: the pair, in this order
Forgetting <iomanip>error: 'setprecision' was not declaredInclude what you use
No prompt before a readProgram appears to "hang"Print a prompt first (and no newline needed)
No echoDisputes about what was typedEcho what was read, labeled

Common student misconceptions

Classroom demonstrations

  1. Fail live: run io_age_check.exe, type abc; show the graceful default path. Then comment out the clear() line, rebuild, and show the next read failing — proving flags persist.
  2. Token vs line: type Data Science 101 into a cin >> s program; print s — only Data arrived. (Full-line reading is L21/Module 15.)
  3. Display vs value: print 19.9 before and after fixed + setprecision(2); then print it with 10 digits to prove the stored value never changed.

Guided student activities

Lab 1 (2 h, runs in this lecture slot per the calendar): students complete labs/lab_manuals/lab_01 — toolchain verification, prompt/echo/validation drills. Lecture hour 2 = lab launch + live build of io_age_check.cpp together, then supervised practice.

Practice problems

Summary

Input and output are streams. cin >> x reads one token and converts it; failure is a flag, checked with if (!(cin >> x)) and repaired with the pair clear() + ignore(...). Formatting manipulators (fixed, setprecision, setw) change display only, never stored values. Prompt, read, echo: the conversational discipline that makes every later lab debuggable. Next (Module 3): what we can compute with the values we now can store and read — operators and expressions.

Exit ticket / formative assessment

  1. Write the one-line check that tests whether cin >> n succeeded.
  2. cin >> a >> b; with input 12 34 56 — what does b hold, and what is left unread?
  3. Why must recovery call clear() before ignore()?

Estimated time allocation (120 min)

SegmentMinutes
Recall (types quiz) + streams-as-faucets10
cin mechanics + chains + echo discipline30
Formatting with <iomanip> (live table)20
Break10
Stream state, failure demo, recovery pattern25
Lab 1 launch (manual walk-through + supervised start)15
Exit ticket + Module 3 preview10
Programming Fundamentals Using C++ · C++17 · 16 weeksBack to top ↑