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

    cout << "What is its street address?\n";

    char address[80];

    cin.getline(address, 80);

    cout << "Year built: " << year << endl;

    cout << "Address: " << address << endl;

    cout << "Done!\n";

    return 0;

}

Running the program in Listing 4.6 would look something like this:

What year was your house built?

1966

What is its street address?

Year built: 1966

Address

Done!

You never get the opportunity to enter the address. The problem is that when cin reads the year, it leaves the newline generated by the Enter key in the input queue. Then cin.getline() reads the newline as an empty line and assigns a null string to the address array. The fix is to read and discard the newline before reading the address. This can be done several ways, including by using get() with a char argument or with no argument, as described in the preceding example. You can make these calls separately:

cin >> year;

cin.get();   // or cin.get(ch);

Or you can concatenate the calls, making use of the fact that the expression cin >> year returns the cin object:

(cin >> year).get();  // or (cin >> year).get(ch);

If you make one of these changes to Listing 4.6, it works properly:

What year was your house built?

1966

What is its street address?

43821 Unsigned Short Street

Year built: 1966

Address: 43821 Unsigned Short Street

Done!

C++ programs frequently use pointers instead of arrays to handle strings. We’ll take up that aspect of strings after talking a bit about pointers. Meanwhile, let’s take a look at a more recent way to handle strings: the C++ string class.

Introducing the string Class

The ISO/ANSI C++98 Standard expanded the C++ library by adding a string class. So now, instead of using a character array to hold a string, you can use a type string variable (or object, to use C++ terminology). As you’ll see, the string class is simpler to use than the array and also provides a truer representation of a string as a type.

To use the string class, a program has to include the string header file. The string class is part of the std namespace, so you have to provide a using directive or declaration or else refer to the class as std::string. The class definition hides the array nature of a string and lets you treat a string much like an ordinary variable. Listing 4.7 illustrates some of the similarities and differences between string objects and character arrays.

Listing 4.7. strtype1.cpp

// strtype1.cpp -- using the C++ string class

#include

#include                // make string class available

int main()

{

    using namespace std;

    char charr1[20];            // create an empty array

    char charr2[20] = "jaguar"; // create an initialized array

    string str1;                // create an empty string object

    string str2 = "panther";    // create an initialized string

    cout << "Enter a kind of feline: ";

    cin >> charr1;

    cout << "Enter another kind of feline: ";

    cin >> str1;                // use cin for input

    cout << "Here are some felines:\n";

    cout << charr1 << " " << charr2 << " "

         << str1 << " " << str2 // use cout for output

         << endl;

    cout << "The third letter in " << charr2 << " is "

         << charr2[2] << endl;

    cout << "The third letter in " << str2 << " is "

         << str2[2] << endl;    // use array notation

    return 0;

}

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

Enter a kind of feline: ocelot

Enter another kind of feline: tiger

Here are some felines:

ocelot jaguar tiger panther

The third letter in jaguar is g

The third letter in panther is n

You should learn from this example that, in many ways, you can use a string object in the same manner as a character array:

• You can initialize a string object to a C-style string.

• You can use cin to store keyboard input in a string object.

• You can use cout to display a string object.

• You can use array notation to access individual characters stored in a string object.

The main difference between string objects and character arrays shown in Listing 4.7 is that you declare a string object as a simple variable, not as an array:

string str1;                // create an empty string object

string str2 = "panther";    // create an initialized string

The class design allows the program to handle the sizing automatically. For instance, the declaration for str1 creates a string object of length zero, but the program automatically resizes str1 when it reads input into str1:

cin >> str1;                // str1 resized to fit input

This makes using a string object both more convenient and safer than using an array. Conceptually, one thinks of an array of char as a collection of char storage units used to store a string but of a string class variable as a single entity representing the string.

C++11 String Initialization

As you might expect by now, C++11 enables list-initialization for C-style strings and string objects:

char first_date[] = {"Le Chapon Dodu"};

char second_date[] {"The Elegant Plate"};

string third_date = {"The Bread Bowl"};

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

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

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

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