Validating Keyboard Input

The biggest problem when working with standard input is that it's reliant on the user properly responding. If the user does not type the right number or format of input, the application cannot be expected to perform properly. This is the old garbage in, garbage out maxim and the reason you'll want to validate input before working with it.

The validity of many answers can be checked with relative ease. For example:

  • Seeing if an age variable is greater than 0 but less than, say, 120

  • Checking that an answer is equal to Yes or No (or Y, y, N, n)

  • Comparing an input against the logical values (like C and F in the temperature-conversion application)

In other cases—such as a temperature conversion where the inputted number can ...

Get C Programming: Visual Quickstart Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.