18. How Else Can I Control Input and Output?

With Built-In I/O Functions

image

There are more ways to produce input and output than with the scanf() and printf() functions. This chapter shows you some of C’s built-in I/O functions that you can use to control I/O. You can use these simple functions to build powerful data-entry routines of your own.

These functions offer the primitive ability to input and output one character at a time. Of course, you also can use the %c format specifier with scanf() and printf() for single characters; however, the character I/O functions explained here are a little easier to use, and they provide some capabilities that scanf() and printf() don’t offer.

putchar() and getchar()

getchar() gets a single character from the keyboard, and putchar() sends a single character to the screen. Figure 18.1 shows you what happens when you use these functions. They work basically the way you think they would. You can use them just about anytime you want to print or input a single character into a variable.

Figure 18.1. getchar() and putchar() input and output single characters.

image

Clue

image

Always include the STDIO.H header file when using this chapter’s I/O functions, just as you do for printf() and scanf().

Note

image

The name getchar() sounds like “get character,” and putchar() sounds like “put character.” Looks as though the designers of C knew what they were doing!

The following program prints C is fun, a character at a time, using putchar() to print each element of the character array in sequence. Notice that strlen() is used to ensure that the for doesn’t output past the end of the string.

image

The getchar() function returns the character input from the keyboard. Therefore, you usually assign the character to a variable or you do something else with it. You can put getchar() on a line by itself like this:

getchar();  /* Does nothing with the character you get */

but most C compilers warn you that this statement is rather useless. The getchar() function would get a character from the keyboard, but then nothing would be done with the character.

Warning

image

The Blackjack program in Appendix B contains a getchar() on a line by itself in getAns(). Believe it or not, this is not necessarily inconsistent with the preceding paragraph. You’ll see why in a few moments.

Here is a program that gets a character one at a time from the keyboard and stores the collected characters in a character array. A series of putchar() functions then prints the array backwards.

image

Clue

image

Notice that the second for loop variable i has no initial value! Actually, it does. i contains the last array subscript entered in the previous getchar()’s for loop. Therefore, the second for loop continues with the value of i left by the first for loop.

Warning

image

The getchar() input character typically is defined as an int, as done here. Integers and characters are about the only C data types you can use interchangeably without worry of typecasts. In some advanced applications, getchar() can return a value that won’t work in a char data type, so use int and you’ll be safe.

Note

image

Aren’t you glad you learned about break? The program keeps getting a character at a time until the user presses Enter (which produces a newline escape sequence). break stops the loop.

The Newline Consideration

Although getchar() gets a single character, control isn’t returned to your program until the user presses Enter. The getchar() function actually instructs C to accept input into a buffer, which is a memory area reserved for input. The buffer isn’t released until the user presses Enter, and then the buffer’s contents are released a character at a time. This means two things. One, the user can press the Backspace key to correct bad character input as long as he or she hasn’t pressed Enter. Two, the Enter keypress is left on the input buffer if you don’t get rid of it.

Getting rid of the Enter keypress is a problem that all beginning C programmers must face. There are several solutions, but none are extremely elegant. Consider the following segment of a program:

image

You would think that if the user typed GT, the G would go in the variable firstInit and the T would go in lastInit, but that’s not what happens. The first getchar() doesn’t finish until the user presses Enter because the G was going to the buffer. Only when the user presses Enter does the G leave the buffer and go to the program; but then the Enter is still on the buffer! Therefore, the second getchar() sends that Enter (actually, the that represents Enter) to lastInit! The T is still left for a subsequent getchar() (if there is one).

Clue

image

One way to fix this problem is to insert an extra getchar() that captures the Enter but doesn’t do anything with it. That’s why the Blackjack program in Appendix B has a getchar() on a line by itself—to capture the Enter and clear the buffer to make room for the next character input.

Here is a workaround for the initial-getting problem:

image

This code requires that the user press Enter between each initial. You don’t have to do anything with the nl variable because nl exists only to hold the in-between newline. As done in the Blackjack game, you don’t even have to save the newline keypress in a variable. The following code works just like the last:

image

Some C compilers issue warning messages when you compile programs with a stand-alone getchar() on lines by themselves. As long as you use these getchar()s for discarding Enter keypresses, you can ignore the compiler warnings.

You also can request the two initials by requiring the Enter keypress after the user enters the two initials like this:

image

If the user types GP and then presses Enter, the G will reside in the firstInit variable and the P in the lastInit variable.

A Little Faster: getch()

A character input function named getch() helps eliminate the leftover Enter keypress that getchar() leaves. getch() is unbuffered—that is, getch() gets whatever keypress the user types immediately and doesn’t wait for an Enter keypress. The drawback to getch() is that the user can’t press the Backspace key to correct bad input. For example, with getchar(), a user could press Backspace if he or she typed a B instead of a D. The B would be taken off the buffer by the Backspace, and the D would be left for getchar() to get once Enter was pressed. Because getch() does not buffer input, there is no chance of pressing Backspace. The following code gets two characters without an Enter keypress following each one:

image

getch() is a little faster than getchar() because it doesn’t wait for an Enter keypress before grabbing the user’s keystrokes and continuing. You therefore don’t need a stand-alone getch() to get rid of the as you do with getchar().

The next chapter explains more built-in functions, including two that quickly input and output strings as easily as this chapter’s I/O functions work with characters.

Rewards

image

• Use getchar() and putchar() to input and output single characters.

• Use a stand-alone getchar() to get rid of the Enter keypress if you don’t want to capture it. You also can create a loop to call getchar() until the return value is , as shown in the sample code.

• Use getch() to get unbuffered single characters as soon as the user types them.

Pitfalls

image

• Don’t use a character I/O function with character variables. Use an int variable instead.

• Don’t forget to print character input using putch() if you want that input echoed on the screen as the user types.

In Review

This chapter’s goal was to explain a few additional input and output functions. The functions presented here are character I/O functions. Unlike scanf() and printf(), the getchar(), getch(), putchar(), and putch() functions input and output single characters at a time.

You’ll often find the getch() and getchar() functions used inside large input routines that build input. This means that these functions get a character at a time from the keyboard and add those characters to an array that is checked against a string value of some kind.

Code Example

image

Code Analysis

This code asks the user a yes-or-no question and waits for the user to respond with a y or an n. The if ensures that the message prints if the user enters n. If the user does not yet have the printer on, the program waits to give the user a chance to turn the printer on. (A report couldn’t be printed otherwise.) The user lets the program know when the printer is turned on by pressing Enter.

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

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