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

    cin.get(input, ArSize);

    while (cin)

    {

        cin.get(next);

        while (next != '\n')    // string didn't fit!

            cin.get(next);      // dispose of remainder

        strcount(input);

        cout << "Enter next line (empty line to quit):\n";

        cin.get(input, ArSize);

    }

    cout << "Bye\n";

    return 0;

}

void strcount(const char * str)

{

    using namespace std;

    static int total = 0;        // static local variable

    int count = 0;               // automatic local variable

    cout << "\"" << str <<"\" contains ";

    while (*str++)               // go to end of string

        count++;

    total += count;

    cout << count << " characters\n";

    cout << total << " characters total\n";

}

Incidentally, the program in Listing 9.9 shows one way to deal with line input that may exceed the size of the destination array. Recall that the cin.get(input,ArSize) input method reads up to the end of the line or up to ArSize - 1 characters, whichever comes first. It leaves the newline character in the input queue. This program uses cin.get(next) to read the character that follows the line input. If next is a newline character, then the preceding call to cin.get(input, ArSize) must have read the whole line. If next isn’t a newline character, there are more characters left on the line. This program then uses a loop to reject the rest of the line, but you can modify the code to use the rest of the line for the next input cycle. The program also uses the fact that attempting to read an empty line with get(char *, int) causes cin to test as false.

Here is the output of the program in Listing 9.9:

Enter a line:

nice pants

"nice pant" contains 9 characters

9 characters total

Enter next line (empty line to quit):

thanks

"thanks" contains 6 characters

15 characters total

Enter next line (empty line to quit):

parting is such sweet sorrow

"parting i" contains 9 characters

24 characters total

Enter next line (empty line to quit):

ok

"ok" contains 2 characters

26 characters total

Enter next line (empty line to quit):

Bye

Note that because the array size is 10, the program does not read more than nine characters per line. Also note that the automatic variable count is reset to 0 each time the function is called. However, the static variable total is set to 0 once at the beginning. After that, total retains its value between function calls, so it’s able to maintain a running total.

Specifiers and Qualifiers

Certain C++ keywords, called storage class specifiers and cv-qualifiers, provide additional information about storage. Here’s a list of the storage class specifiers:

auto (eliminated as a specifier in C++11)

register

static

extern

thread_local (added by C++11)

mutable

You’ve already seen most of these, and you can use no more than one of them in a single declaration, except that thread_local can be used with static or extern. To review, prior to C++11, the keyword auto could be used in a declaration to document that the variable is an automatic variable. (In C++11, auto is used for automatic type deduction.) The keyword register is used in a declaration to indicate the register storage class, which, in C++11, simply is an explicit way of saying the variable is automatic. The keyword static, when used with a file-scope declaration, indicates internal linkage. When used with a local declaration, it indicates static storage duration for a local variable. The keyword extern indicates a reference declaration—that is, that the declaration refers to a variable defined elsewhere. The keyword thread_local indicates that the duration of the variable is the duration of the containing thread. A thread_local variable is to a thread much as a regular static variable is to the whole program. The keyword mutable is explained in terms of const, so let’s look at the cv-qualifiers first before returning to mutable.

Cv-Qualifiers

Here are the cv-qualifiers:

const

volatile

(As you may have guessed, cv stands for const and volatile.) The most commonly used cv-qualifier is const, and you’ve already seen its purpose: It indicates that memory, after initialized, should not be altered by a program. We’ll come back to const in a moment.

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

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

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

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