Главная » Просмотр файлов » B. Stroustrup - The C++ Programming Language

B. Stroustrup - The C++ Programming Language (794319), страница 26

Файл №794319 B. Stroustrup - The C++ Programming Language (B. Stroustrup - The C++ Programming Language) 26 страницаB. Stroustrup - The C++ Programming Language (794319) страница 262019-05-09СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 26)

Since indexing starts from 0, s gets the value Stroustrup.The replace() operation replaces a substring with a value. In this case, the substring starting at 0with length 5 is Niels; it is replaced by nicholas. Finally, I replace the initial character with itsuppercase equivalent. Thus, the final value of name is Nicholas Stroustrup. Note that the replacement string need not be the same size as the substring that it is replacing.Naturally, strings can be compared against each other and against string literals. For example:string incantation;void respond(const string& answer){if (answer == incantation) {// perform magic}else if (answer == "yes") {// ...}// ...}Thestring library is describedstring are presented in the Stringin Chapter 36.

The most common techniques for implementingexample (§19.3).4.3 Stream I/OThe standard library provides formatted character input and output through the iostream library.The input operations are typed and extensible to handle user-defined types. This section is a verybrief introduction to the use of iostreams; Chapter 38 is a reasonably complete description of theiostream library facilities.Other forms of user interaction, such as graphical I/O, are handled through libraries that are notpart of the ISO standard and therefore not described here.4.3.1 OutputThe I/O stream library defines output for every built-in type. Further, it is easy to define output of auser-defined type (§4.3.3). The operator << (‘‘put to’’) is used as an output operator on objects of92A Tour of C++: Containers and AlgorithmsChapter 4type ostream; cout is the standard output stream and cerr is the standard stream for reporting errors.By default, values written to cout are converted to a sequence of characters.

For example, to outputthe decimal number 10, we can write:void f(){cout << 10;}This places the character 1 followed by the character 0 on the standard output stream.Equivalently, we could write:void g(){int i {10};cout << i;}Output of different types can be combined in the obvious way:void h(int i){cout << "the value of i is ";cout << i;cout << '\n';}For h(10), the output will be:the value of i is 10People soon tire of repeating the name of the output stream when outputting several related items.Fortunately, the result of an output expression can itself be used for further output. For example:void h2(int i){cout << "the value of i is " << i << '\n';}This h2() produces the same output as h().A character constant is a character enclosed in single quotes.

Note that a character is output asa character rather than as a numerical value. For example:void k(){int b = 'b';// note: char implicitly converted to intchar c = 'c';cout << 'a' << b << c;}The integer value of the character 'b' is 98 (in the ASCII encoding used on the C++ implementationthat I used), so this will output a98c.Section 4.3.2Input934.3.2 InputThe standard library offers istreams for input.

Like ostreams, istreams deal with character stringrepresentations of built-in types and can easily be extended to cope with user-defined types.The operator >> (‘‘get from’’) is used as an input operator; cin is the standard input stream. Thetype of the right-hand operand of >> determines what input is accepted and what is the target of theinput operation. For example:void f(){int i;cin >> i;double d;cin >> d;// read an integer into i// read a double-precision floating-point number into d}This reads a number, such as 1234, from the standard input into the integer variable i and a floatingpoint number, such as 12.34e5, into the double-precision floating-point variable d.Often, we want to read a sequence of characters.

A convenient way of doing that is to read intoa string. For example:void hello(){cout << "Please enter your name\n";string str;cin >> str;cout << "Hello, " << str << "!\n";}If you type in Eric the response is:Hello, Eric!By default, a whitespace character (§7.3.2), such as a space, terminates the read, so if you enter Ericpretending to be the ill-fated king of York, the response is still:BloodaxeHello, Eric!You can read a whole line (including the terminating newline character) using the getline() function.For example:void hello_line(){cout << "Please enter your name\n";string str;getline(cin,str);cout << "Hello, " << str << "!\n";}With this program, the input Eric Bloodaxe yields the desired output:Hello, Eric Bloodaxe!94A Tour of C++: Containers and AlgorithmsChapter 4The newline that terminated the line is discarded, so cin is ready for the next input line.The standard strings have the nice property of expanding to hold what you put in them; youdon’t have to precalculate a maximum size.

So, if you enter a couple of megabytes of semicolons,the program will echo pages of semicolons back at you.4.3.3 I/O of User-Defined TypesIn addition to the I/O of built-in types and standard strings, the iostream library allows programmersto define I/O for their own types. For example, consider a simple type Entry that we might use torepresent entries in a telephone book:struct Entry {string name;int number;};We can define a simple output operator to write an Entry using a {"name",number} format similar tothe one we use for initialization in code:ostream& operator<<(ostream& os, const Entry& e){return os << "{\"" << e.name << "\", " << e.number << "}";}A user-defined output operator takes its output stream (by reference) as its first argument andreturns it as its result.

See §38.4.2 for details.The corresponding input operator is more complicated because it has to check for correct formatting and deal with errors:istream& operator>>(istream& is, Entry& e)// read { "name" , number } pair. Note: formatted with { " " , and }{char c, c2;if (is>>c && c=='{' && is>>c2 && c2=='"') { // star t with a { "string name;// the default value of a string is the empty string: ""while (is.get(c) && c!='"')// anything before a " is part of the namename+=c;if (is>>c && c==',') {int number = 0;if (is>>number>>c && c=='}') { // read the number and a }e = {name,number};// assign to the entryreturn is;}}}is.setf(ios_base::failbit);return is;// register the failure in the stream}An input operation returns a reference to itsistreamwhich can be used to test if the operationSection 4.3.3I/O of User-Defined Types95succeeded.

For example, when used as a condition, is>>c means ‘‘Did we succeed at reading fromis into c?’’The is>>c skips whitespace by default, but is.get(c) does not, so that this Entry-input operatorignores (skips) whitespace outside the name string, but not within it. For example:{ "John Marwood Cleese" , 123456{"Michael Edward Palin",987654}}We can read such a pair of values from input into an Entry like this:for (Entry ee; cin>>ee; ) // read from cin into eecout << ee << '\n'; // write ee to coutThe output is:{"John Marwood Cleese", 123456}{"Michael Edward Palin", 987654}See §38.4.1 for more technical details and techniques for writing input operators for user-definedtypes. See §5.5 and Chapter 37 for a more systematic technique for recognizing patterns in streamsof characters (regular expression matching).4.4 ContainersMost computing involves creating collections of values and then manipulating such collections.Reading characters into a string and printing out the string is a simple example.

A class with themain purpose of holding objects is commonly called a container. Providing suitable containers fora given task and supporting them with useful fundamental operations are important steps in theconstruction of any program.To illustrate the standard-library containers, consider a simple program for keeping names andtelephone numbers. This is the kind of program for which different approaches appear ‘‘simple andobvious’’ to people of different backgrounds. The Entry class from §4.3.3 can be used to hold asimple phone book entry. Here, we deliberately ignore many real-world complexities, such as thefact that many phone numbers do not have a simple representation as a 32-bit int.4.4.1 vectorThe most useful standard-library container is vector. A vector is a sequence of elements of a giventype. The elements are stored contiguously in memory:vector:elem:sz:0:1:2:3:4:5:6The Vector examples in §3.2.2 and §3.4 give an idea of the implementation of vector and §13.6 and§31.4 provide an exhaustive discussion.96A Tour of C++: Containers and AlgorithmsChapter 4We can initialize a vector with a set of values of its element type:vector<Entry> phone_book = {{"David Hume",123456},{"Karl Popper",234567},{"Bertrand Arthur William Russell",345678}};Elements can be accessed through subscripting:void print_book(const vector<Entry>& book){for (int i = 0; i!=book.size(); ++i)cout << book[i] << '\n';}As usual, indexing starts at 0 so that book[0] holds the entry for David Hume.

Характеристики

Тип файла
PDF-файл
Размер
18,76 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6384
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее