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

The strcat() function would attempt to copy all 12 characters into the site array, thus overrunning adjacent memory. This might cause the program to abort, or the program might continue running but with corrupted data. The string class, with its automatic resizing as necessary, avoids this sort of problem. The C library does provide cousins to strcat() and strcpy(), called strncat() and strncpy(), that work more safely by taking a third argument to indicate the maximum allowed size of the target array, but using them adds another layer of complexity in writing programs.

Notice the different syntax used to obtain the number of characters in a string:

int len1 = str1.size();     // obtain length of str1

int len2 = strlen(charr1);  // obtain length of charr1

The strlen() function is a regular function that takes a C-style string as its argument and that returns the number of characters in the string. The size() function basically does the same thing, but the syntax for it is different. Instead of appearing as a function argument, str1 precedes the function name and is connected to it with a dot. As you saw with the put() method in Chapter 3, this syntax indicates that str1 is an object and that size() is a class method. A method is a function that can be invoked only by an object belonging to the same class as the method. In this particular case, str1 is a string object, and size() is a string method. In short, the C functions use a function argument to identify which string to use, and the C++ string class objects use the object name and the dot operator to indicate which string to use.

More on string Class I/O

As you’ve seen, you can use cin with the >> operator to read a string object and cout with the << operator to display a string object using the same syntax you use with a C-style string. But reading a line at a time instead of a word at time uses a different syntax. Listing 4.10 shows this difference.

Listing 4.10. strtype4.cpp

// strtype4.cpp -- line input

#include

#include                // make string class available

#include               // C-style string library

int main()

{

    using namespace std;

    char charr[20];

    string str;

    cout << "Length of string in charr before input: "

         << strlen(charr) << endl;

    cout << "Length of string in str before input: "

         << str.size() << endl;

    cout << "Enter a line of text:\n";

    cin.getline(charr, 20);     // indicate maximum length

    cout << "You entered: " << charr << endl;

    cout << "Enter another line of text:\n";

    getline(cin, str);          // cin now an argument; no length specifier

    cout << "You entered: " << str << endl;

    cout << "Length of string in charr after input: "

         << strlen(charr) << endl;

    cout << "Length of string in str after input: "

         << str.size() << endl;

    return 0;

}

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

Length of string in charr before input: 27

Length of string in str before input: 0

Enter a line of text:

peanut butter

You entered: peanut butter

Enter another line of text:

blueberry jam

You entered: blueberry jam

Length of string in charr after input: 13

Length of string in str after input: 13

Note that the program says the length of the string in the array charr before input is 27, which is larger than the size of the array! Two things are going on here. The first is that the contents of an uninitialized array are undefined. The second is that the strlen() function works by starting at the first element of the array and counting bytes until it reaches a null character. In this case, the first null character doesn’t appear until several bytes after the end of the array. Where the first null character appears in uninitialized data is essentially random, so you very well could get a different numeric result using this program.

Also note that the length of the string in str before input is 0. That’s because an uninitialized string object is automatically set to zero size.

This is the code for reading a line into an array:

cin.getline(charr, 20);

The dot notation indicates that the getline() function is a class method for the istream class. (Recall that cin is an istream object.) As mentioned earlier, the first argument indicates the destination array, and the second argument is the array size, which getline() used to avoid overrunning the array.

This is the code for reading a line into a string object:

getline(cin,str);

There is no dot notation, which indicates that this getline() is not a class method. So it takes cin as an argument that tells it where to find the input. Also there isn’t an argument for the size of the string because the string object automatically resizes to fit the string.

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

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

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

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