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

Each statement can be either a single statement or a statement block delimited by braces (see Figure 6.2). The entire if else construct counts syntactically as a single statement.

Figure 6.2. The structure of if else statements.

For example, suppose you want to alter incoming text by scrambling the letters while keeping the newline character intact. In that case, each line of input is converted to an output line of equal length. This means you want the program to take one course of action for newline characters and a different course of action for all other characters. As Listing 6.2 shows, if else makes this task easy. The listing also illustrates the std:: qualifier, one of the alternatives to a using directive.

Listing 6.2. ifelse.cpp

// ifelse.cpp -- using the if else statement

#include

int main()

{

    char ch;

    std::cout << "Type, and I shall repeat.\n";

    std::cin.get(ch);

    while (ch != '.')

    {

        if (ch == '\n')

            std::cout << ch;     // done if newline

        else

            std::cout << ++ch;   // done otherwise

        std::cin.get(ch);

    }

// try ch + 1 instead of ++ch for interesting effect

    std::cout << "\nPlease excuse the slight confusion.\n";

        //  std::cin.get();

        //  std::cin.get();

    return 0;

}

Here’s some sample output from the program in Listing 6.2:

Type, and I shall repeat.

An ineffable joy suffused me as I beheld

Bo!jofggbcmf!kpz!tvggvtfe!nf!bt!J!cfifme

the wonders of modern computing.

uif!xpoefst!pg!npefso!dpnqvujoh

Please excuse the slight confusion.

Note that one of the comments in Listing 6.2 suggests that changing ++ch to ch+1 has an interesting effect. Can you deduce what it will be? If not, try it out and then see if you can explain what’s happening. (Hint: Think about how cout handles different types.)

Formatting if else Statements

Keep in mind that the two alternatives in an if else statement must be single statements. If you need more than one statement, you must use braces to collect them into a single block statement. Unlike some languages, such as BASIC and FORTRAN, C++ does not automatically consider everything between if and else a block, so you have to use braces to make the statements a block. The following code, for example, produces a compiler error:

if (ch == 'Z')

    zorro++;       // if ends here

    cout << "Another Zorro candidate\n";

else               // wrong

    dull++;

    cout << "Not a Zorro candidate\n";

The compiler sees it as a simple if statement that ends with the zorro++; statement.

Then there is a cout statement. So far, so good. But then there is what the compiler perceives as an unattached else, and that is flagged as a syntax error.

You add braces to group statements into a single statement block:

if (ch == 'Z')

{                       // if true block

    zorro++;

    cout << "Another Zorro candidate\n";

}

else

{                      // if false block

    dull++;

    cout << "Not a Zorro candidate\n";

}

Because C++ is a free-form language, you can arrange the braces as you like, as long as they enclose the statements. The preceding code shows one popular format. Here’s another:

if (ch == 'Z') {

    zorro++;

    cout << "Another Zorro candidate\n";

    }

else {

    dull++;

    cout << "Not a Zorro candidate\n";

    }

The first form emphasizes the block structure for the statements, whereas the second form more closely ties the blocks to the keywords if and else. Either style is clear and consistent and should serve you well; however, you may encounter an instructor or employer with strong and specific views on the matter.

The if else if else Construction

Computer programs, like life, might present you with a choice of more than two selections. You can extend the C++ if else statement to meet such a need. As you’ve seen, the else should be followed by a single statement, which can be a block. Because an if else statement itself is a single statement, it can follow an else:

if (ch == 'A')

    a_grade++;               // alternative # 1

else

    if (ch == 'B')           // alternative # 2

        b_grade++;           // subalternative # 2a

    else

        soso++;              // subalternative # 2b

If ch is not 'A', the program goes to the else. There, a second if else subdivides that alternative into two more choices. C++’s free formatting enables you to arrange these elements into an easier-to-read format:

if (ch == 'A')

    a_grade++;              // alternative # 1

else if (ch == 'B')

    b_grade++;              // alternative # 2

else

    soso++;                 // alternative # 3

This looks like a new control structure—an if else if else structure. But actually it is one if else contained within a second. This revised format looks much cleaner, and it enables you to skim through the code to pick out the different alternatives. This entire construction still counts as one statement.

Listing 6.3 uses this preferred formatting to construct a modest quiz program.

Listing 6.3. ifelseif.cpp

// ifelseif.cpp -- using if else if else

#include

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

Все книги серии 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.

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

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