C++ · Beginner level

Beginner level · Module 5: C++ Console Project · Lesson 3 of 3

Robust Input and Testing

Recover from invalid input, write a test plan and fix what it reveals before presenting.

In this lesson you will

  • Detect and recover from failed std::cin reads
  • Write and run a test plan with edge cases

Key concepts

std::cin.fail()clear() and ignore()edge casetest record

The lesson

If the user types letters where std::cin >> expects a number, the stream enters a fail state and every later read fails too, often causing an endless loop. Check the read, then call std::cin.clear() and std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') before asking again.

Wrap this in a function such as readDouble(prompt, min, max) and use it for every number. One well-tested function is better than validation copied in many places.

Write a test record with normal values, boundaries and invalid input, and record the actual results. Fix any failures, then rerun the whole record before the demonstration.

Step by step

  1. Type letters at a number prompt and observe the failure.
  2. Write readDouble with clear() and ignore().
  3. Use it for every numeric input.
  4. Run a test plan of at least eight cases.

Practice activity

Finish the Water Point Log with robust input and a completed test record, then demonstrate it.

Expected result: No input crashes or locks the program, and the test record shows every case passing.

Check your understanding

  1. What must you do after std::cin fails?

    Show answer

    Call clear() to reset the state and ignore() to discard the bad input.

  2. Why put validation in one function?

    Show answer

    So it is written and tested once and used consistently everywhere.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.