Sams Teach Yourself C in 21 Days

(singke) #1

Working with Complex Data in C++ ................................................................


You have learned that there are a number of different data types that can be used to store
information. You’ve seen that a type intvariable can be used to track simple numbers. A
charcan be used to track individual characters. A character array can be used to track a
string.
In the real world, you encounter many different objects, such as a person’s name, a
shape, an invoice, an electronic book, a checkbook transaction, and so on. The simple
data types provided in C and in C++ don’t effectively track all these complex objects.
You learned that structures are a way of tracking these more complex data objects. You
can use structures to create your own user-defined data types. With structures you can
create data types to track complex data such as a name, a rectangle, an invoice, or a
checkbook transaction. For example, you can track the time using the following struc-
ture:
struct time
{
int hours;
int minutes;
int seconds;
};
With this time structure, you can declare a number of time variables to use in your pro-
grams. For example, you can create a program to store a start time and an end time as
shown in Listing B3.1.

LISTINGB3.1 endtime.cpp. Using a time structure
1: //Program using a time structure
2: //
3: #include <iostream.h>
4:
5: struct time {
6: int hours;
7: int minutes;
8: int seconds;
9: };
10:
11: void print_time(struct time tm);
12:
13: int main(int argc, char* argv[])
14: {
15: struct time start_time;
16: struct time end_time;
17:

666 Bonus Day 3

38 448201x-Bonus3 8/13/02 11:19 AM Page 666

Free download pdf