I l @ ve RuBoard |
As you saw in Chapter 7, "C Control Statements: Branching and Jumps," getchar() and putchar() perform input and output one character at a time. That method might strike you as a rather silly way of doing things. After all, you can easily read groupings larger than a single character, but this method does suit the capability of a computer. Furthermore, this approach is the heart of most programs that deal with text, that is, with ordinary words. To remind yourself of how these functions work, examine Listing 8.1, a very simple example. All it does is fetch characters from keyboard input and send them to the screen. This process is called echoing the input . We use a while loop that terminates when the # character is encountered .
/* echo.c -- repeats input */ #include <stdio.h> int main (void) { char ch; while ((ch = getchar()) != '#') putchar(ch); return 0; }
On most systems, the definitions of getchar() and putchar() are in the system file stdio.h , which is why we have included that file in the program. (Typically, getchar() and putchar() are not true functions, but are defined using preprocessor macros, a topic we'll cover in Chapter 16, "The C Preprocessor and the C Library." ) Using this program produces exchanges like this:
Hello, there. I would[enter] Hello, there. I would like a #3 bag of potatoes.[enter] like a
After watching this program run, you might wonder why you must type a whole line before the input is echoed . You might also wonder if there is a better way to terminate input. Using a particular character, such as # , to terminate input prevents you from using that character in the text. To answer these questions, you have to look at how C programs handle keyboard input. In particular, you need to examine buffering and the concept of a standard input file.
I l @ ve RuBoard |