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

After it gets data, the program uses an if else statement to comment if no data was entered (that is, if the first entry was a negative number) and to process the data if any is present.

Setting Up Ranges with &&

The && operator also lets you set up a series of if else if else statements, with each choice corresponding to a particular range of values. Listing 6.6 illustrates the approach. It also shows a useful technique for handling a series of messages. Just as a pointer-to-char variable can identify a single string by pointing to its beginning, an array of pointers-to-char can identify a series of strings. You simply assign the address of each string to a different array element. Listing 6.6 uses the qualify array to hold the addresses of four strings. For example, qualify[1] holds the address of the string "mud tug-of-war\n". The program can then use qualify[1] as it would any other pointer to a string—for example, with cout or with strlen() or strcmp(). Using the const qualifier protects these strings from accidental alterations.

Listing 6.6. more_and.cpp

// more_and.cpp -- using the logical AND operator

#include

const char * qualify[4] =       // an array of pointers

{                               // to strings

    "10,000-meter race.\n",

    "mud tug-of-war.\n",

    "masters canoe jousting.\n",

    "pie-throwing festival.\n"

};

int main()

{

    using namespace std;

    int age;

    cout << "Enter your age in years: ";

    cin >> age;

    int index;

    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;

    cout << "You qualify for the " << qualify[index];

    return 0;

}

Here is a sample run of the program in Listing 6.6:

Enter your age in years: 87

You qualify for the pie-throwing festival.

The entered age doesn’t match any of the test ranges, so the program sets index to 3 and then prints the corresponding string.

Program Notes

In Listing 6.6, the expression age > 17 && age < 35 tests for ages between the two values—that is, ages in the range 18–34. The expression age >= 35 && age < 50 uses the >= operator to include 35 in its range, which is 35–49. If the program used age > 35 && age < 50, the value 35 would be missed by all the tests. When you use range tests, you should check that the ranges don’t have holes between them and that they don’t overlap. Also you need to be sure to set up each range correctly; see the sidebar “Range Tests,” later in this section.

The if else statement serves to select an array index, which, in turn, identifies a particular string.

Range Tests

Note that each part of a range test should use the AND operator to join two complete relational expressions:

if (age > 17 && age < 35)   // OK

Don’t borrow from mathematics and use the following notation:

if (17 < age < 35)          // Don't do this!

If you make this mistake, the compiler won’t catch it as an error because it is still valid C++ syntax. The < operator associates from left to right, so the previous expression means the following:

if ( (17 < age) < 35)

But 17 < age is either true, or 1, or else false, or 0. In either case, the expression 17 < age is less than 35, so the entire test is always true!

The Logical NOT Operator: !

The ! operator negates, or reverses the truth value of, the expression that follows it. That is, if expression is true, then !expression is false—and vice versa. More precisely, if expression is true, or nonzero, then !expression is false. Incidentally, many people call the exclamation point bang, making !x “bang-ex” and !!x “bang-bang-ex.”

Usually you can more clearly express a relationship without using the ! operator:

if (!(x > 5))                 // if (x <= 5) is clearer

But the ! operator can be useful with functions that return true/false values or values that can be interpreted that way. For example, strcmp(s1,s2) returns a nonzero (true) value if the two C-style strings s1 and s2 are different from each other and a zero value if they are the same. This implies that !strcmp(s1,s2) is true if the two strings are equal.

Listing 6.7 uses the technique of applying the ! operator to a function return value to screen numeric input for suitability to be assigned to type int. The user-defined function is_int(), which we’ll discuss further in a moment, returns true if its argument is within the range of values that can be assigned to type int. The program then uses the test while(!is_int(num)) to reject values that don’t fit in the range.

Listing 6.7. not.cpp

// not.cpp -- using the not operator

#include

#include

bool is_int(double);

int main()

{

    using namespace std;

    double num;

    cout << "Yo, dude! Enter an integer value: ";

    cin >> num;

    while (!is_int(num))    // continue while num is not int-able

    {

        cout << "Out of range -- please try again: ";

        cin >> num;

    }

    int val = int (num);    // type cast

    cout << "You've entered the integer " << val << "\nBye\n";

    return 0;

}

bool is_int(double x)

{

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

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

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

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