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 be any value—validation is trickier. One technique you can use involves the scanf() function itself. Because that function returns the number of items it read in, you can use that returned value to determine if the input matched the assumed type. To explain more clearly, let's rewrite the temp_conversion application. This new version will also make use of a technique for ignoring extraneous input (see the sidebar).

To validate user input

1.
Open temp_conversion.c (Script 5.4) in your text editor or IDE.

2.
Declare a third char variable (Script 5.5):

char junk;

Script 5.5. Input validation requires thought and testing but is crucial to reliable, professional applications. Here, the act of reading input is written as the tested condition before any calculations are made.


The junk variable will be used within a while loop to help read in and discard extraneous input (see the sidebar, “Ignoring Input”).

3.
Rewrite the scanf() line so that it's part of a conditional:

if (scanf ("%f %c", &temp_i,
 &which_i) == 2) {

The scanf() function will return the number of items it successfully read in. As it has been formatted in this example to receive a float followed by a character, if the keyed input was correct, scanf() should return the number 2 as two values were read and assigned to variables.

That knowledge allows you to place the entire scanf() code within a conditional. The condition specifically checks if the scanf() function returns a value that is equal to 2. If this condition is true, you know that one float and one character were successfully read in and you can proceed with the calculations.

If you find this syntax to be too complicated, you can rewrite it like so:

int n;
n = scanf ("%f %c", &temp_i,
 &which_i);
if (n == 2) {

4.
Make all of the functionality of the original program part of the if conditional.

The switch and if-else conditionals that were at the heart of the original application are now the resulting code for the if part of the main (scanf()) conditional.

5.
Complete the main conditional:

} else {
     printf ("You failed to use the
 proper syntax.
");
}

If the scanf() function does not return the number 2, a problem occurred and this message is printed.

6.
Add a while loop to read in any more input:

do {
     junk = getchar();
} while (junk != '
' );

Following the syntax outlined in the sidebar, this while loop reads in everything after the last read character (which should be C or F).

7.
Delete the second getchar() function at the end of the application.

Since the do…while loop should take care of any extraneous stuff, only one getchar() call is required on Windows.

8.
Save the file as temp_conversion2.c, compile, and debug as necessary.

9.
Run the application, keying in both valid (Figure 5.12) and invalid (Figure 5.13) input.

Figure 5.12. After adding more input validation, the application works as it had before if the input is entered correctly.


Figure 5.13. The input is now validated so that no conversions are attempted using improper input.


✓ Tips

  • There are many ways to validate input; which you use depends on the type, number, and format of the input expected. In this chapter you've seen a couple of options (using scanf() and checking values against a switch). The most important thing to know is that you should not assume people will always properly use an application.

    Ignoring Input

    As you may have experienced when using some of the examples in this chapter, improper input can throw off an application. For example, if you enter Yes instead of just Y, two extra characters are present (plus the newline created by pressing Return or Enter). These extra characters can throw off your application if further input is read later on. For example, if one use of getchar() expects either Y or N and a later use of getchar() expects another Y or N and the user types in Yes to the first prompt, the second prompt will read in the e following the Y. This was obviously not the intent.

    To ignore and discard input, you can use the getchar() function within a while loop to read until the end of a line. The syntax is

    char var;
    do {
       var = getchar();
    } while ( var != '
    ' );
    

    In short, this loop continues to read a single character from the standard input, assigning this value to var, until it encounters a newline (created when the user presses Return or Enter). At that time, the loop will be exited and the rest of the application will continue to execute.


  • Some validation can be accomplished using the ctype.h library. It adds several functions, such as isalpha(), isdigit(), and isspace(), that check if a single character is of a certain type. The ctype.h file also adds conversion functions to your applications. These functions include tolower() and toupper(), for converting the cases of single characters.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset