C++ - Input Validation

Overview

Estimated time: 25–35 minutes

Validate inputs and recover from errors using stream state checks and clear/ignore patterns.

Learning Objectives

  • Check std::cin state and handle invalid input.
  • Use std::cin.clear() and std::cin.ignore() to recover.

Example

#include 
#include 
int x{};
if (!(std::cin >> x)){
  std::cin.clear();
  std::cin.ignore(std::numeric_limits::max(), '\n');
}

Common Pitfalls

  • Looping on bad input without clearing flags causes infinite loops.