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

The break and continue Statements

The break and continue statements enable a program to skip over parts of the code. You can use the break statement in a switch statement and in any of the loops. It causes program execution to pass to the next statement following the switch or the loop. The continue statement is used in loops and causes a program to skip the rest of the body of the loop and then start a new loop cycle (see Figure 6.4).

Figure 6.4. The structure of continue and break statements.

Listing 6.12 shows how the two statements work. The program lets you enter a line of text. The loop echoes each character and uses break to terminate the loop if the character is a period. This shows how you can use break to terminate a loop from within when some condition becomes true. Next the program counts spaces but not other characters. The loop uses continue to skip over the counting part of the loop when the character isn’t a space.

Listing 6.12. jump.cpp

// jump.cpp -- using continue and break

#include

const int ArSize = 80;

int main()

{

    using namespace std;

    char line[ArSize];

    int spaces = 0;

    cout << "Enter a line of text:\n";

    cin.get(line, ArSize);

    cout << "Complete line:\n" << line << endl;

    cout << "Line through first period:\n";

    for (int i = 0; line[i] != '\0'; i++)

    {

        cout << line[i];    // display character

        if (line[i] == '.') // quit if it's a period

            break;

        if (line[i] != ' ') // skip rest of loop

            continue;

        spaces++;

    }

    cout << "\n" << spaces << " spaces\n";

    cout << "Done.\n";

    return 0;

}

Here’s a sample run of the program in Listing 6.12:

Enter a line of text:

Let's do lunch today. You can pay!

Complete line:

Let's do lunch today. You can pay!

Line through first period:

Let's do lunch today.

3 spaces

Done.

Program Notes

Note that whereas the continue statement causes the program in Listing 6.12 to skip the rest of the loop body, it doesn’t skip the loop update expression. In a for loop, the continue statement makes the program skip directly to the update expression and then to the test expression. For a while loop, however, continue makes the program go directly to the test expression. So any update expression in a while loop body following the continue would be skipped. In some cases, that could be a problem.

This program doesn’t have to use continue. Instead, it could use this code:

if (line[i] == ' ')

    spaces++;

However, the continue statement can make a program more readable when several statements follow the continue. That way, you don’t need to make all those statements part of an if statement.

C++, like C, also has a goto statement. A statement like this means to jump to the location bearing the paris: label:

goto paris;

That is, you can have code like this:

char ch;

cin >> ch;

if (ch == 'P')

      goto paris;

cout << ...

...

paris: cout << "You've just arrived at Paris.\n";

In most circumstances (some would say in all circumstances), using goto is a bad hack, and you should use structured controls, such as if else, switch, continue, and the like, to control program flow.

Number-Reading Loops

Say you’re preparing a program to read a series of numbers into an array. You want to give the user the option to terminate input before filling the array. One way to do this is utilize how cin behaves. Consider the following code:

int n;

cin >> n;

What happens if the user responds by entering a word instead of a number? Four things occur in such a mismatch:

• The value of n is left unchanged.

• The mismatched input is left in the input queue.

• An error flag is set in the cin object.

• The call to the cin method, if converted to type bool, returns false.

The fact that the method returns false means that you can use non-numeric input to terminate a number-reading loop. The fact that non-numeric input sets an error flag means that you have to reset the flag before the program can read more input. The clear() method, which also resets the end-of-file (EOF) condition (see Chapter 5), resets the bad input flag. (Either bad input or the EOF can cause cin to return false. Chapter 17, “Input, Output, and Files,” discusses how to distinguish between the two cases.) Let’s look at a couple examples that illustrate these techniques.

Say you want to write a program that calculates the average weight of your day’s catch of fish. There’s a five-fish limit, so a five-element array can hold all the data, but it’s possible that you could catch fewer fish. Listing 6.13 uses a loop that terminates if the array is full or if you enter non-numeric input.

Listing 6.13. cinfish.cpp

// cinfish.cpp -- non-numeric input terminates loop

#include

const int Max = 5;

int main()

{

    using namespace std;

// get data

    double fish[Max];

    cout << "Please enter the weights of your fish.\n";

    cout << "You may enter up to " << Max

            << " fish .\n";

    cout << "fish #1: ";

    int i = 0;

    while (i < Max && cin >> fish[i]) {

        if (++i < Max)

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

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

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

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

Все жанры