I l @ ve RuBoard |
By now, you probably expect a sample program at the beginning of each chapter, and I won't disappoint you. Listing 4.1 presents a program that engages in a dialogue with the user .
/* talkback.c -- nosy, informative program */ #include <stdio.h> #include <string.h> /* for strlen() prototype */ #define DENSITY 62.4 /* human density in lbs per cu ft */ int main(void) { float weight, volume; int size, letters; char name[40]; /* name is an array of 40 chars */ printf("Hi! What's your first name?\n"); scanf("%s", name); printf("%s, what's your weight in pounds?\n", name); scanf("%f", &weight); size = sizeof name; letters = strlen(name); volume = weight / DENSITY; printf("Well, %s, your volume is %2.2f cubic feet.\n", name, volume); printf("Also, your first name has %d letters,\n", letters); printf("and we have %d bytes to store it in.\n", size); return 0; }
(Recall that some compilers, such as Think C for the Macintosh, require %ld for printing sizeof quantities .) Running talkback produces results such as the following:
Hi! what's your first name? Angelica Angelica, what's your weight in pounds? 132.5 Well, Angelica, your volume is 2.12 cubic feet. Also, your first name has 8 letters, and we have 40 bytes to store it in.
Here are the main new features of this program:
It uses an array to hold a character string . Here, someone's name is read into the array, which, in this case, is a series of 40 consecutive bytes in memory, each able to hold a single character value.
It uses the %s conversion specification to handle the input and output of the string. Note that name , unlike weight , does not use the & prefix when used with scanf() . (As you'll see later, both &weight and name are addresses.)
It uses the C preprocessor to define the symbolic constant DENSITY to represent the value 62.4 .
It uses the C function strlen() to find the length of a string.
The C approach might seem a little complex compared with the input/output of, say, BASIC. However, this complexity buys a finer control of I/O and a greater program efficiency. It is surprisingly easy once you get used to it.
Let's investigate these new ideas.
I l @ ve RuBoard |