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

C++ has inherited from C a handy package of character-related functions, prototyped in the cctype header file (ctype.h, in the older style), that simplify such tasks as determining whether a character is an uppercase letter or a digit or punctuation. For example, the isalpha(ch) function returns a nonzero value if ch is a letter and a zero value otherwise. Similarly, the ispunct(ch) function returns a true value only if ch is a punctuation character, such as a comma or period. (These functions have return type int rather than bool, but the usual bool conversions allow you to treat them as type bool.)

Using these functions is more convenient than using the AND and OR operators. For example, here’s how you might use AND and OR to test whether a character ch is an alphabetic character:

if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))

Compare that to using isalpha():

if (isalpha(ch))

Not only is isalpha() easier to use, it is more general. The AND/OR form assumes that character codes for A through Z are in sequence, with no other characters having codes in that range. This assumption is true for ASCII codes, but it isn’t always true in general.

Listing 6.8 demonstrates some functions from the cctype family. In particular, it uses isalpha(), which tests for alphabetic characters; isdigits(), which tests for digit characters, such as 3; isspace(), which tests for whitespace characters, such as newlines, spaces, and tabs; and ispunct(), which tests for punctuation characters. The program also reviews the if else if structure and using a while loop with cin.get(char).

Listing 6.8. cctypes.cpp

// cctypes.cpp -- using the ctype.h library

#include

#include               // prototypes for character functions

int main()

{

    using namespace std;

    cout << "Enter text for analysis, and type @"

            " to terminate input.\n";

    char ch;

    int whitespace = 0;

    int digits = 0;

    int chars = 0;

    int punct = 0;

    int others = 0;

    cin.get(ch);                // get first character

    while (ch != '@')            // test for sentinel

    {

        if(isalpha(ch))         // is it an alphabetic character?

            chars++;

        else if(isspace(ch))    // is it a whitespace character?

            whitespace++;

        else if(isdigit(ch))    // is it a digit?

            digits++;

        else if(ispunct(ch))    // is it punctuation?

            punct++;

        else

            others++;

        cin.get(ch);            // get next character

    }

    cout << chars << " letters, "

         << whitespace << " whitespace, "

         << digits << " digits, "

         << punct << " punctuations, "

         << others << " others.\n";

    return 0;

}

Here is a sample run of the program in Listing 6.8 (note that the whitespace count includes newlines):

Enter text for analysis, and type @ to terminate input.

AdrenalVision International producer Adrienne Vismonger

announced production of their new 3-D film, a remake of

"My Dinner with Andre," scheduled for 2013. "Wait until

you see the the new scene with an enraged Collossipede!"@

177 letters, 33 whitespace, 5 digits, 9 punctuations, 0 others.

Table 6.4 summarizes the functions available in the cctype package. Some systems may lack some of these functions or have additional ones.

Table 6.4. The cctype Character Functions

The ?: Operator

C++ has an operator that can often be used instead of the if else statement. This operator is called the conditional operator, written ?:, and, for you trivia buffs, it is the only C++ operator that requires three operands. The general form looks like this:

expression1 ? expression2 : expression3

If expression1 is true, then the value of the whole conditional expression is the value of expression2. Otherwise, the value of the whole expression is the value of expression3. Here are two examples that show how the operator works:

5 > 3 ? 10 : 12  // 5 > 3 is true, so expression value is 10

3 == 9? 25 : 18  // 3 == 9 is false, so expression value is 18

We can paraphrase the first example this way: If 5 is greater than 3, the expression evaluates to 10; otherwise, it evaluates to 12. In real programming situations, of course, the expressions would involve variables.

Listing 6.9 uses the conditional operator to determine the larger of two values.

Listing 6.9. condit.cpp

// condit.cpp -- using the conditional operator

#include

int main()

{

    using namespace std;

    int a, b;

    cout << "Enter two integers: ";

    cin >> a >> b;

    cout << "The larger of " << a << " and " << b;

    int c = a > b ? a : b;   // c = a if a > b, else c = b

    cout << " is " << c << endl;

    return 0;

}

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

Enter two integers: 25 28

The larger of 25 and 28 is 28

The key part of the program is this statement:

int c = a > b ? a : b;

It produces the same result as the following statements:

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

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

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

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