Inputting a Single Character

A simple interactive application will make a request (for a number or a Yes/No answer) and respond accordingly. Doing so can be described as a four-step process:

1.
Prompting the user, indicating the type of information requested (Figure 5.1)

Figure 5.1. Letting the user know what type (and often, which format) of information is requested is an important facet of your applications.


2.
Reading the input typed into the keyboard

3.
Validating that the input is of the proper format

4.
Reacting based on the value of the input

This chapter will teach all of these steps from the ground up.

The simplest type of input to be read (Step 2) is a single character. This is accomplished using the getchar() function, which you've already seen (you've been using it to pause applications until the Enter or Return key is pressed). The getchar() function reads a single inputted character and assigns that to a variable:

char gender;
gender = getchar();

As a demonstration of this idea, the following example will ask the user to respond to a Yes or No question.

To read a single character

1.
Create a new file or project in your text editor or IDE.

2.
Type the standard beginning lines of code (Script 5.1):

/* Script 5.1 - donut.c */
#include <stdio.h>
int main (void) {

Script 5.1. Single-character input can be read from the keyboard using the getchar() function.


3.
Create a character variable:

char answer;

The char data type was briefly introduced in Chapter 2, “Introduction to Data Types.” In this case, the variable answer will be able to hold a single character. Comments are added (see the corresponding script) to indicate what type and format of data is expected to be stored in this variable.

4.
Prompt the user and read in the reply:

printf("Would you like a donut?
 [Y/N] ");

This line prints the question being asked and indicates within square brackets the type and format the answer is expected to be in. Using square brackets like this is a common technique, giving a visual cue to the user as to how the application should be used.

Notice that, unlike previous examples, no newline character ( ) is added to the end of the printf(). Because of this, the cursor—and therefore the user's answer—will appear on the same line as the prompt. Similar to using the square brackets, this is in no way a requirement but instead provides a nicer interface (Figure 5.2).

Figure 5.2. The donut application prompts the user to answer a simple question.


5.
Read in the typed reply:

answer = getchar();

This line reads in the first character typed and assigns this to the answer variable. It will read in whatever character is first typed, including numbers or white space.

6.
Begin a conditional that prints different messages based on what the user entered.

switch (answer) {

Since answer is a single-character variable, a switch conditional can be used here (switch works only on char and integer values). You could also use an if-else if-else conditional here, but a switch will work better.

7.
Add the first two cases:

case 'Y':
case 'y':
     printf ("Mmmm...donuts.
");
     break;

Since the switch will perform a case-sensitive comparison, two cases are added to see if Yes (in the form of Y or y) was typed. If either of these cases is true, then the print statement is executed and the switch is exited, thanks to the break.

Understanding Input and Output

The C language provides the stdio.h library file to assist in the handling of input and output (stdio refers to standard input/output). By including this file in an application, you have access to such common functions as printf().

The standard input for an application is the keyboard, where input is typed. The standard output is the screen, where text is displayed within a console or terminal window. These aren't the only options, though. For example, input can be read from a text file, and output can be sent to a system or error log.

In this chapter you'll be working with the standard input and output, but many of the same processes apply in other situations, such as reading and writing to files. You'll see this in Chapter 12, “File Input and Output.”


8.
Add two more cases to handles No's:

case 'N':
case 'n':
     printf ("You don't want a
 donut!?! But they're so sweet
 and tasty!
");
     break;

This is a repeat of Step 7, using different values for the cases and a different message to be printed. As a reminder, normally you want a break for every case in a switch statement. In this example, there are fall-through cases (Y and N), allowing multiple cases to have the same result.

9.
Add a default case and complete the switch:

    default:
            printf ("Um...you were
 supposed to enter either 'Y'
 or 'N'.
");
            break;
}

The default case will be called if the typed answer is not one of the accepted values (Y, y, N, or n). The break isn't required at the end of this case, but it's a good idea to include it.

10.
Type two more calls to the getchar() function:

getchar();
getchar();

In previous applications the getchar() function was called once to pause execution until the user presses Return or Enter. This is necessary on some platforms (in particular, Windows) so that the console window does not close before you have the chance to view the results.

In this and the following examples, an extra call to the same function may be required. This would be because, for example, the first character typed in (Y, y, N, or n) would be read by the first getchar() and the Return or Enter pressed after that would be read by the second getchar(). Once again, this would close the console window before you had the opportunity to see the results.

If you are not having problems with the console or terminal window closing too quickly, you may omit these lines.

11.
Complete the main function:

      return 0;
}

12.
Save the file as donut.c, compile, and debug as necessary.

13.
Run the application, entering different values (Figure 5.3) to see the results.

Figure 5.3. The application responds differently based on the answer submitted by the user.


✓ Tips

  • Because the getchar() function reads in only a single character, if the user types Y5089ljj in response to the donut application, that will still be treated as just Y (Figure 5.4).

    Figure 5.4. The getchar() function literally records only the first character, so Y5089ljj is the same as just Y (Figure 5.2) in this example.

  • The opposite of getchar() is putchar(), which sends a single character to the output. This line will print the value of the gender variable (assuming it's a single character):

    putchar (gender);
    
  • Whenever you need to read only a single character, getchar() is definitely the way to go. Other methods covered in this chapter will also work on single characters, but they aren't as fast and require more complex code.


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

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