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

So why is one getline() an istream class method and the other getline() not? The istream class was part of C++ long before the string class was added. So the istream design recognizes basic C++ types such as double and int, but it is ignorant of the string type. Therefore, there are istream class methods for processing double, int, and the other basic types, but there are no istream class methods for processing string objects.

Because there are no istream class methods for processing string objects, you might wonder why code like this works:

cin >> str;  // read a word into the str string object

It turns out that code like the following does (in disguised notation) use a member function of the istream class:

cin >> x;  // read a value into a basic C++ type

But the string class equivalent uses a friend function (also in disguised notation) of the string class. You’ll have to wait until Chapter 11 to see what a friend function is and how this technique works. In the meantime, you can use cin and cout with string objects and not worry about the inner workings.

Other Forms of String Literals

C++, recall, has the wchar_t type in addition to char. And C++11 adds the char16_t and char32_t types. It’s possible to create arrays of these types and string literals of these types. C++ uses the L, u, and U prefixes, respectively, for string literals of these types. Here’s an example of how they can be used:

wchar_t title[] = L"Chief Astrogator";  // w_char string

char16_t name[] = u"Felonia Ripova";    // char_16 string

char32_t car[] = U"Humber Super Snipe"; // char_32 string

C++11 also supports an encoding scheme for Unicode characters called UTF-8. In this scheme a given character may be stored in anywhere from one 8-bit unit, or octet, to four 8-bit units, depending on the numeric value. C++ uses the u8 prefix to indicate string literals of that type.

Another C++11 addition is the raw string. In a raw string, characters simply stand for themselves. For example, the sequence \n is not interpreted as representing the newline character; instead, it is two ordinary characters, a backslash and an n, and it would display as those two characters onscreen. As another example, you can use a simple " inside a string instead of the more awkward \" we used in Listing 4.8. Of course, if you allow a " inside a string literal, you no longer can use it to delimit the ends of a string. Therefore, raw strings use "( and )" as delimiters, and they use an R prefix to identify them as raw strings:

cout << R"(Jim "King" Tutt uses "\n" instead of endl.)" << '\n';

This would display the following:

Jim "King" Tutt uses \n instead of endl.

The standard string literal equivalent would be this:

cout << "Jim \"King\" Tutt uses \" \\n\" instead of endl." << '\n';

Here we had to use \\ to display \ because a single \ is interpreted as the first character of an escape sequence.

If you press the Enter or Return key while typing a raw string, that not only moves the cursor to the next line onscreen, it also places a carriage return character in the raw string.

What if you want to display the combination )" in a raw string? (Who wouldn’t?) Won’t the compiler interpret the first occurrence of )" as the end of the string? Yes, it will. But the raw string syntax allows you to place additional characters between the opening " and (. This implies that the same additional characters must appear between the final ) and ". So a raw string beginning with R"+* must terminate with )+*". Thus, the statement

cout << R"+*("(Who wouldn't?)", she whispered.)+*" << endl;

would display the following:

"(Who wouldn't?)", she whispered.

In short, the default delimiters of "( and )" have been replaced with "+*( and )+*". You can use any of the members of the basic character set as part of the delimiter other than the space, the left parenthesis, the right parenthesis, the backslash, and control characters such as a tab or a newline.

The R prefix can be combined with the other string prefixes to produce raw strings of wchar_t and so on. It can be either the first or the last part of a compound prefix: Ru, UR, and so on.

Now let’s go on to another compound type—the structure.

Introducing Structures

Suppose you want to store information about a basketball player. You might want to store his or her name, salary, height, weight, scoring average, free-throw percentage, assists, and so on. You’d like some sort of data form that could hold all this information in one unit. An array won’t do. Although an array can hold several items, each item has to be the same type. That is, one array can hold 20 ints and another can hold 10 floats, but a single array can’t store ints in some elements and floats in other elements.

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

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

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

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