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

Listing 15.6 offers a short program for testing the new class.

Listing 15.6. nested.cpp

// nested.cpp -- using a queue that has a nested class

#include

#include

#include "queuetp.h"

int main()

{

    using std::string;

    using std::cin;

    using std::cout;

    QueueTP cs(5);

    string temp;

    while(!cs.isfull())

    {

        cout << "Please enter your name. You will be "

                "served in the order of arrival.\n"

                "name: ";

        getline(cin, temp);

        cs.enqueue(temp);

    }

    cout << "The queue is full. Processing begins!\n";

    while (!cs.isempty())

    {

        cs.dequeue(temp);

        cout << "Now processing " << temp << "...\n";

    }

    return 0;

}

Here is a sample run of the program in Listings 15.5 and 15.6:

Please enter your name. You will be served in the order of arrival.

name: Kinsey Millhone

Please enter your name. You will be served in the order of arrival.

name: Adam Dalgliesh

Please enter your name. You will be served in the order of arrival.

name: Andrew Dalziel

Please enter your name. You will be served in the order of arrival.

name: Kay Scarpetta

Please enter your name. You will be served in the order of arrival.

name: Richard Jury

The queue is full. Processing begins!

Now processing Kinsey Millhone...

Now processing Adam Dalgliesh...

Now processing Andrew Dalziel...

Now processing Kay Scarpetta...

Now processing Richard Jury...

Exceptions

Programs sometimes encounter runtime problems that prevent them from continuing normally. For example, a program may try to open an unavailable file, or it may request more memory than is available, or it may encounter values it cannot abide. Usually, programmers try to anticipate such calamities. C++ exceptions provide a powerful and flexible tool for dealing with these situations. Exceptions are a relatively recent addition to C++, so some older compilers haven’t implemented them. Also some compilers turn this feature off by default, so you may have to use the compiler options to turn it on.

Before examining exceptions, let’s look at some of the more rudimentary options available to programmers. As a test case, let’s look at a function that calculates the harmonic mean of two numbers. The harmonic mean of two numbers is defined as the inverse of the average of the inverses. This can be reduced to the following expression:

2.0 × x × y / (x + y)

Note that if y is the negative of x, this formula results in division by zero, a rather undesirable operation. Many newer compilers handle division by zero by generating a special floating-point value that represents infinity; cout displays this value as Inf, inf, INF, or something similar. Other compilers may produce programs that crash when division by zero occurs. It is best to write code that behaves in the same controlled fashion on all systems.

Calling abort()

One way to handle this is to have the function call the abort() function if one argument is the negative of the other. The abort() function has its prototype in the cstdlib (or stdlib.h) header file. A typical implementation, if called, sends a message such as “abnormal program termination” to the standard error stream (the same as the one used by cerr) and terminates the program. It also returns an implementation-dependent value that indicates failure to the operating system or, if the program was initiated by another program, to the parent process. Whether abort() flushes file buffers (that is, memory areas used to store material for transfers to and from files) depends on the implementation. If you prefer, you can use exit(), which does flush file buffers, but without displaying a message. Listing 15.7 shows a short program that uses abort().

Listing 15.7. error1.cpp

//error1.cpp -- using the abort() function

#include

#include

double hmean(double a, double b);

int main()

{

    double x, y, z;

    std::cout << "Enter two numbers: ";

    while (std::cin >> x >> y)

    {

        z = hmean(x,y);

        std::cout << "Harmonic mean of " << x << " and " << y

            << " is " << z << std::endl;

        std::cout << "Enter next set of numbers : ";

    }

    std::cout << "Bye!\n";

    return 0;

}

double hmean(double a, double b)

{

    if (a == -b)

    {

        std::cout << "untenable arguments to hmean()\n";

        std::abort();

    }

    return 2.0 * a * b / (a + b);

}

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

Enter two numbers: 3 6

Harmonic mean of 3 and 6 is 4

Enter next set of numbers : 10 -10

untenable arguments to hmean()

abnormal program termination

Note that calling the abort() function from hmean() terminates the program directly, without returning first to main(). In general, different compilers issue different abort messages. Here is another such message:

This application has requested the Runtime to terminate it

in an unusual way. Please contact the application's support

team for more information.

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

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

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

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