Solution for Exercise 8-18

ex0818

#include <stdio.h>

int main()
{
    char code;

    printf("Enter the error letter (A, B, C): ");
    scanf("%c",&code);
    switch(code)
    {
        case 'A':
            puts("Drive Fault, not your fault.");
            break;
        case 'B':
            puts("Illegal format, call a lawyer.");
            break;
        case 'C':
            puts("Bad filename, spank it.");
            break;
        default:
            puts("That's not A, B, or C");
    }
    return(0);
}

Output

Enter the error letter (A, B, C): A
Drive Fault, not your fault.

Notes

* Changes required for this Exercise:

Line 5: Change the variable type to char.
Line 7: Modify the prompt string.
Line 8: Change the placeholder to %c
Line 11: Change the case test to letter 'A'
Line 14: Change the case test to letter 'B'
Line 17: Change the case test to letter 'C'
Line 21: Change the string.

* It's okay if you used getchar() in Line 8 instead of scanf(). Both functions do essentially the same thing for single character input.

* It's important that the characters being compared are specified in single quotes, as shown at Lines 11, 14, and 17.

* It's also possible to test for lowercase letters as well. You must double-up on the case statements and use fall-through as described in the book. Can you do it?