Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Using a Structure in a Program

Поиск

Now that we’ve covered some of the main features of structures, it’s time to put the ideas together in a structure-using program. Listing 1 illustrates these points about a structure. Also, it shows how to initialize one.

 

Listing 1

struct inflatable { // structure declaration

char name[20];

float volume;

double price;

};

 

void main() {

inflatable guest = {

“Glorious Gloria”, // name value

1.88, // volume value

29.99 // price value

}; // guest is a structure variable of type inflatable

 

// It’s initialized to the indicated values

inflatable pal = {

“Audacious Arthur”,

3.12,

32.99

}; // pal is a second variable of type inflatable

 

cout << “Expand your guest list with “ << guest.name;

cout << “ and “ << pal.name << “!\n”; // pal.name is the name member of the

// pal variable

cout << “You can have both for $”;

cout << guest.price + pal.price << “!\n”;

}

 

Here is the output from the program in Listing 1:

Expand your guest list with Glorious Gloria and Audacious Arthur!

You can have both for $62.98!

 

Program Notes

One important matter related to the program in Listing 1 is where to place the structure declaration. You could place the declaration inside the main() function, just after the opening brace. The second choice, and the one made here, is to place it outside and preceding main(). When a declaration occurs outside any function, it’s called an external declaration. The external declaration can be used by all the functions following it, whereas the internal declaration can be used only by the function in which the declaration is found. Most often, you want an external structure declaration so that all the functions can use structures of that type (see Fig. 2).

 

Fig. 2. Local and external structure declarations

 

Variables, too, can be defined internally or externally, with external variables shared among functions.

As with arrays, you use a comma-separated list of values enclosed in a pair of braces. The program places one value per line, but you can place them all on the same line. Just remember to separate items with commas:

 

inflatable duck = {“Daphne”, 0.12, 9.98};

 

Other Structure Properties

C++ makes user-defined types as similar as possible to built-in types. For example, you can pass structures as arguments to a function, and you can have a function use a structure as a return value. Also, you can use the assignment operator (=) to assign one structure to another of the same type. Doing so causes each member of one structure to be set to the value of the corresponding member in the other structure, even if the member is an array. This kind of assignment is called memberwise assignment, Listing 2 provides an example.

 

Listing 2

struct inflatable {

char name[20];

float volume;

double price;

};

 

void main() {

using namespace std;

 

inflatable bouquet = {

“sunflowers”,

0.20,

12.49

};

inflatable choice;

 

cout << “bouquet: “ << bouquet.name << “ for $”;

cout << bouquet.price << endl;

choice = bouquet; // assign one structure to another

cout << “choice: “ << choice.name << “ for $”;

cout << choice.price << endl;

}

 

Here’s the output from the program in Listing 2:

bouquet: sunflowers for $12.49

choice: sunflowers for $12.49

 

As you can see, member wise assignment is at work, for the members of the choice structure are assigned the same values stored in the bouquet structure.

You can combine the definition of a structure form with the creation of structure variables. To do so, you follow the closing brace with the variable name or names:

 

struct perks {

int key_number;

char car[12];

} mr_smith, ms_jones; // two perks variables

 

You even can initialize a variable you create in this fashion:

 

struct perks {

int key_number;

char car[12];

} mr_glitz = {

7, // value for mr_glitz.key_number member

“Packard” // value for mr_glitz.car member

};

 

However, keeping the structure definition separate from the variable declarations usually makes a program easier to read and follow.

Unlike C structures, for example, C++ structures can have member functions in addition to member variables. But these more advanced features most typically are used with classes rather than structures.

 

Arrays of Structures

It’s also possible to create arrays whose elements are structures. The technique is exactly the same as for creating arrays of the fundamental types. For example, to create an array of 100 inflatable structures, you could do the following:

 

inflatable gifts[100]; // array of 100 inflatable structures

 

This makes gifts an array of inflatables. Hence each element of the array, such as gifts[0] or gifts[99], is an inflatable object and can be used with the membership operator:

 

cin >> gifts[0].volume; // use volume member of first struct

cout << gifts[99].price << endl; // display price member of last struct

 

Keep in mind that gifts itself is an array, not a structure, so constructions such as gifts.price are not valid.

To initialize an array of structures, you combine the rule for initializing arrays (a brace-enclosed, comma-separated list of values for each element) with the rule for structures (a brace-enclosed, comma-separated list of values for each member). Because each element of the array is a structure, its value is represented by a structure initialization. Thus, you wind up with a brace-enclosed, comma-separated list of values, each of which itself is a brace-enclosed, comma-separated list of values:

 

inflatable guests[2] = { // initializing an array of structs

{“Bambi”, 0.5, 21.99}, // first structure in array

{“Godzilla”, 2000, 565.99} // next structure in array

};

 

Listing 3 shows a short example that uses an array of structures. Note that because guests is an array of inflatable, guest[0] is type inflatable, so you can use it with the dot opera-tor to access a member of the inflatable structure.

 

Listing 3

struct inflatable {

char name[20];

float volume;

double price;

};

 

void main() {

inflatable guests[2] = { // initializing an array of structs

{“Bambi”, 0.5, 21.99}, // first structure in array

{“Godzilla”, 2000, 565.99} // next structure in array

};

cout << “The guests “ << guests[0].name << “ and “ << guests[1].name << “\nhave a combined volume of “ << guests[0].volume + guests[1].volume << “ cubic feet.\n”;

}

 

Here is the output of the program in Listing 3:

The guests Bambi and Godzilla

have a combined volume of 2000.5 cubic feet.

 

Lab Overview

2.1. Read the theory and try Control Exercises.

2.2. Develop the algorithm flowchart to create input data and handle structures array according to individual case from the Table below.

2.3. Write the program code according to the developed algorithm. Dynamic variables, pointers, user-defined functions should be used.

2.4. Debug the program, run it and make screenshots.

2.5. Prepare the Lab Report according to the required structure.

 

# Structures array Operation on array
1. Books Find a book with a minimum number of pages
2. Vegetables Find vegetables with red color
3. Computers Output a configuration of the most expensive computer
4. Films Find a film with a highest budget
5. Shoes Output shoes with a price more than average one
6. Cell phones Output Nokia cell phones
7. Students Calculate the group average rating
8. Laptops Output laptops with a screen diagonal more than 15 inches
9. Fruits Output fruits with weight less than 200g
10. Shirts Find a shirt with a lowest price
11. Bags Find a bag with a highest number of pockets
12. Soundtracks Output soundtracks of the film “Transformers”
13. Drinks Output non-alcoholic drinks
14. Pens Output black pens with a price more than $100
15. Workers Find a worker with a highest salary
16. Cars Output cars of 2012 year
17. Songs Output songs with a rating bellow the indicated one
18. Soft Output freeware soft
19. Animals Calculate the total weight of all animals in the database
20. Countries Output countries with a population more than the population in Ukraine
21. Soccer Teams Output teams which won Champion League more than 3 times
22. Tanks Output middle weight tanks
23. Motorcycles Output motorcycles with engine volume more than 50 sm3
24. Rock groups Output rock groups from Ukraine
25. Cosmetics Output goods from Avon

 

Report Structure

- Title page

- Task overview

- Algorithm’s flowchart

- Program code

- Program running screenshots

- Conclusions

 

Control Exercises

4.1. Devise a structure declaration that describes a fish. The structure should include the kind, the weight in whole ounces, and the length in fractional inches.

4.2. Declare a variable of the type defined in the previous exercise and initialize it.

4.3. Write a code fragment that dynamically allocates a structure of the type described in Exercise 4.1 Question 6 and then reads a value for the kind member of the structure.

 

References

5.1. Juan Soulié. C++ Language Tutorial. – 2007. – p. 77-81.

5.2. Sharam Hekmat. C++ Essentials. – PragSoft Corporation 2005. – p. 110-114.

5.3. Prata S. C++ Primer Plus (5th Edition). – Sams, 2004. – p. 131-138.

 


Lab #6. STRINGS

Goal: Study how to create C++ programs which handle strings

Theory

Introduction to Strings

A string is a series of characters stored in consecutive bytes of memory. C++ has two ways of dealing with strings. The first, taken from C and often called a C-style string, is the first one this chapter examines. Later, this chapter discusses an alternative method based on a string class library.

The idea of a series of characters stored in consecutive bytes implies that you can store a string in an array of char, with each character kept in its own array element. Strings provide a convenient way to store text information, such as messages to the user (“Please tell me your secret Swiss bank account number”) or responses from the user (“You must be joking”). C-style strings have a special feature: The last character of every string is the null character. This character, written \0, is the character with ASCII code 0, and it serves to mark the string’s end. For example, consider the following two declarations:

 

char dog [5] = { ‘b’, ‘e’, ‘a’, ‘u’, ‘x’}; // not a string!

char cat[5] = {‘f’, ‘a’, ‘t’, ‘s’, ‘\0’}; // a string!

 

Both of these arrays are arrays of char, but only the second is a string. The null character plays a fundamental role in C-style strings. For example, C++ has many functions that handle strings, including those used by cout. They all work by processing a string character-by-character until they reach the null character. If you ask cout to display a nice string like cat in the preceding example, it displays the first four characters, detects the null character, and stops. But if you are ungracious enough to tell cout to display the dog array from the preceding example, which is not a string, cout prints the five letters in the array and then keeps march-ing through memory byte-by-byte, interpreting each byte as a character to print, until it reached a null character. Because null characters, which really are bytes set to zero, tend to be common in memory, the damage is usually contained quickly; nonetheless, you should not treat nonstring character arrays as strings.

The cat array example makes initializing an array to a string look tedious—all those single quotes and then having to remember the null character. Don’t worry. There is a better way to initialize a character array to a string. Just use a quoted string, called a string constant or string literal, as in the following:

 

char bird[11] = “Mr. Cheeps”; // the \0 is understood

char fish[] = “Bubbles”; // let the compiler count

 

Quoted strings always include the terminating null character implicitly, so you don’t have to spell it out (see Fig. 1). Also, the various C++ input facilities for reading a string from keyboard input into a char array automatically add the terminating null character for you. (If, when you run the program in Listing 1, you discover that you have to use the keyword static to initialize an array, you have to use it with these char arrays, too.)

 

Fig. 1. Initializing an array to a string

 

Of course, you should make sure the array is large enough to hold all the characters of the string, including the null character. Initializing a character array with a string constant is one case where it may be safer to let the compiler count the number of elements for you. There is no harm, other than wasted space, in making an array larger than the string. That’s because functions that work with strings are guided by the location of the null character, not by the size of the array. C++ imposes no limits on the length of a string.

Note that a string constant (with double quotes) is not interchangeable with a character constant (with single quotes). A character constant, such as ‘S’, is a shorthand notation for the code for a character. On an ASCII system, ‘S’ is just another way of writing 83. Thus, the statement

 

char shirt_size = ‘S’; // this is fine

 

assigns the value 83 to shirt_size. But “S” represents the string consisting of two characters, the S and the \0 characters. Even worse, “S” actually represents the memory address at which the string is stored. So a statement like

 

char shirt_size = “S”; // illegal type mismatch

 

attempts to assign a memory address to shirt_size! Because an address is a separate type in C++, a C++ compiler won’t allow this sort of nonsense. (We’ll return to this point later in this chapter, after we’ve discussed pointers.)

 



Поделиться:


Последнее изменение этой страницы: 2016-04-18; просмотров: 260; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.144.8.68 (0.006 с.)