Читаем C++ Primer Plus полностью

Your employees think you are the finest CEO

in the industry. The board of directors think

you are the finest CEO in the industry.

Please enter 1, 2, 3, 4, or 5:

1) alarm           2) report

3) alibi           4) comfort

5) quit

2

It's been an excellent week for business.

Sales are up 120%. Expenses are down 35%.

Please enter 1, 2, 3, 4, or 5:

1) alarm           2) report

3) alibi           4) comfort

5) quit

6

That's not a choice.

Please enter 1, 2, 3, 4, or 5:

1) alarm           2) report

3) alibi           4) comfort

5) quit

5

Bye!

The while loop terminates when the user enters 5. Entering 1 through 4 activates the corresponding choice from the switch list, and entering 6 triggers the default statements.

Note that input has to be an integer for this program to work correctly. If, for example, you enter a letter, the input statement will fail, and the loop will cycle endlessly until you kill the program. To deal with those who don’t follow instructions, it’s better to use character input.

As noted earlier, this program needs the break statements to confine execution to a particular portion of a switch statement. To see that this is so, you can remove the break statements from Listing 6.10 and see how it works afterward. You’ll find, for example, that entering 2 causes the program to execute all the statements associated with case labels 2, 3, 4, and the default. C++ works this way because that sort of behavior can be useful. For one thing, it makes it simple to use multiple labels. For example, suppose you rewrote Listing 6.10 using characters instead of integers as menu choices and switch labels. In that case, you could use both an uppercase and a lowercase label for the same statements:

char choice;

cin >> choice;

while (choice != 'Q' && choice != 'q')

{

    switch(choice)

    {

        case 'a':

        case 'A': cout << "\a\n";

                  break;

        case 'r':

        case 'R': report();

                  break;

        case 'l':

        case 'L': cout << "The boss was in all day.\n";

                  break;

        case 'c':

        case 'C': comfort();

                  break;

        default : cout << "That's not a choice.\n";

    }

    showmenu();

    cin >> choice;

}

Because there is no break immediately following case 'a', program execution passes on to the next line, which is the statement following case 'A'.

Using Enumerators as Labels

Listing 6.11 illustrates using enum to define a set of related constants and then using the constants in a switch statement. In general, cin doesn’t recognize enumerated types (it can’t know how you will define them), so the program reads the choice as an int. When the switch statement compares the int value to an enumerator case label, it promotes the enumerator to int. Also the enumerators are promoted to type int in the while loop test condition.

Listing 6.11. enum.cpp

// enum.cpp -- using enum

#include

// create named constants for 0 - 6

enum {red, orange, yellow, green, blue, violet, indigo};

int main()

{

    using namespace std;

    cout << "Enter color code (0-6): ";

    int code;

    cin >> code;

    while (code >= red && code <= indigo)

    {

        switch (code)

        {

            case red     : cout << "Her lips were red.\n"; break;

            case orange  : cout << "Her hair was orange.\n"; break;

            case yellow  : cout << "Her shoes were yellow.\n"; break;

            case green   : cout << "Her nails were green.\n"; break;

            case blue    : cout << "Her sweatsuit was blue.\n"; break;

            case violet  : cout << "Her eyes were violet.\n"; break;

            case indigo  : cout << "Her mood was indigo.\n"; break;

        }

        cout << "Enter color code (0-6): ";

        cin >> code;

    }

    cout << "Bye\n";

    return 0;

}

Here’s sample output from the program in Listing 6.11:

Enter color code (0-6): 3

Her nails were green.

Enter color code (0-6): 5

Her eyes were violet.

Enter color code (0-6): 2

Her shoes were yellow.

Enter color code (0-6): 8

Bye

switch and if else

Both the switch statement and the if else statement let a program select from a list of alternatives. The if else is the more versatile of the two. For example, it can handle ranges, as in the following:

if (age > 17 && age < 35)

    index = 0;

else if (age >= 35 && age < 50)

    index = 1;

else if (age >= 50 && age < 65)

    index = 2;

else

    index = 3;

The switch statement, on the other hand, isn’t designed to handle ranges. Each switch case label must be a single value. Also that value must be an integer (which includes char), so a switch statement can’t handle floating-point tests. And the case label value must be a constant. If your alternatives involve ranges or floating-point tests or comparing two variables, you should use if else.

If, however, all the alternatives can be identified with integer constants, you can use a switch or an if else statement. Because that’s precisely the situation that the switch statement is designed to process, the switch statement is usually the more efficient choice in terms of code size and execution speed, unless there are only a couple alternatives from which to choose.

Tip

If you can use either an if else if sequence or a switch statement, the usual practice is to use switch if you have three or more alternatives.

Перейти на страницу:

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных

Похожие книги

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

Алексей Анатольевич Гладкий

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

Алексей Анатольевич Гладкий

Финансы / Программирование, программы, базы данных