I l @ ve RuBoard |
Gwen Glenn wants to print an inventory of her books. She would like to print a variety of information for each book: title, author, publisher, copyright date, the number of pages, the number of copies, and the dollar value. Some of these items, such as the titles, can be stored in an array of strings. Other items require an array of int or an array of float . With seven different arrays, keeping track of everything can get complicated, especially if Gwen wants to generate several complete lists, one sorted by title, one sorted by author, one sorted by value, and so on. A better solution is to use one array, in which each member contained all the information about one book.
Gwen needs a data form, then, that can contain both strings and numbers and somehow keep the information separate. The C structure meets this need. To see how a structure is set up and how it works, we'll start with a limited example. To simplify the problem, we will impose two restrictions. First, we'll include only title, author, and current market value. Second, we'll limit the inventory to one book. If you have more books than that, don't worry; we'll extend the program soon.
Look at the program in Listing 14.1 and its output. Then read our explanation of the main points.
/* book.c -- one-book inventory */ #include <stdio.h> #define MAXTITL 41 /* maximum length of title + 1 */ #define MAXAUTL 31 /* maximum length of author's name + 1 */ struct book { /* structure template: tag is book */ char title[MAXTITL]; char author[MAXAUTL]; float value; }; /* end of structure template */ int main(void) { struct book libry; /* declare libry as book-type variable */ printf("Please enter the book title.\n"); gets(libry.title); /* access to the title portion */ printf("Now enter the author.\n"); gets(libry.author); printf("Now enter the value.\n"); scanf("%f", &libry.value); printf("%s by %s: $%.2f\n",libry.title, libry.author, libry.value); printf("%s: \"%s\" ($%.2f)\n", libry.author, libry.title, libry.value); return 0; }
Here is a sample run:
Please enter the book title. Chicken of the Alps Now enter the author. Bismo Lapoult Now enter the value. 14.95 Chicken of the Alps by Bismo Lapoult: .95 Bismo Lapoult: "Chicken of the Alps" (.95)
The structure created in Listing 14.1 has three parts (called members or fields): one to store the title, one to store the author, and one to store the value. These are the three main skills you must acquire:
Setting up a format or layout for a structure
Declaring a variable to fit that layout
Gaining access to the individual components of a structure variable
I l @ ve RuBoard |