Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming

Здесь есть возможность читать онлайн «Bruce Eckel - Thinking In C++. Volume 2 - Practical Programming» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Год выпуска: 2003, ISBN: 2003, Издательство: Prentice Hall, Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Thinking In C++. Volume 2: Practical Programming: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Thinking In C++. Volume 2: Practical Programming»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Best selling author Bruce Eckel has joined forces with Chuck Allison to write
, the sequel to the highly received and best selling
. Eckel is the master of teaching professional programmers how to quickly learn cutting edge topics in C++ that are glossed over in other C++ books. In
, the authors cover the finer points of exception handling, defensive programming and string and stream processing that every C++ programmer needs to know. Special attention is given to generic programming where the authors reveal little known techniques for effectively using the Standard Template Library. In addition, Eckel and Allison demonstrate how to apply RTTI, design patterns and concurrent programming techniques to improve the quality of industrial strength C++ applications. This book is targeted at programmers of all levels of experience who want to master C++.

Thinking In C++. Volume 2: Practical Programming — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Thinking In C++. Volume 2: Practical Programming», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

typedef basic_istream istream;

All the classes mentioned earlier are defined via similar type definitions. There are also type definitions for all stream classes using wchar_t(the wide character type discussed in Chapter 3) instead of char. We’ll look at these at the end of this chapter. The basic_iostemplate defines functions common to both input and output, but that depends on the underlying character type (we won’t use these much). The template basic_istreamdefines generic functions for input, and basic_ostreamdoes the same for output. The classes for file and string streams introduced later add functionality for their specific stream types .

In the iostreams library, two operators are overloaded to simplify the use of iostreams. The operator <<is often referred to as an inserter for iostreams, and the operator >>is often referred to as an extractor .

Extractors parse the information that’s expected by the destination object according to its type. To see an example of this, you can use the cinobject, which is the iostream equivalent of stdinin C, that is, redirectable standard input. This object is predefined whenever you include the header .

int i;

cin >> i;

float f;

cin >> f;

char c;

cin >> c;

char buf[100];

cin >> buf;

There’s an overloaded operator >>for every built-in data type. You can also overload your own, as you’ll see later .

To find out what you have in the various variables, you can use the coutobject (corresponding to standard output; there’s also a cerrobject corresponding to standard error) with the inserter <<: .

cout << "i = ";

cout << i;

cout << "\n";

cout << "f = ";

cout << f;

cout << "\n";

cout << "c = ";

cout << c;

cout << "\n";

cout << "buf = ";

cout << buf;

cout << "\n";

This is notably tedious and doesn’t seem like much of an improvement over printf( ), despite improved type checking. Fortunately, the overloaded inserters and extractors are designed to be chained together into a more complicated expression that is much easier to write (and read): .

cout << "i = " << i << endl;

cout << "f = " << f << endl;

cout << "c = " << c << endl;

cout << "buf = " << buf << endl;

Defining inserters and extractors for your own classes is just a matter of overloading the associated operators to do the right things, namely:

· Make the first parameter a non- constreference to the stream ( istreamfor input, ostreamfor output)

· Perform the operation by insert/extracting data to/from the stream (by processing the components of the object, of course)

· Return a reference to the stream

The stream should be non- constbecause processing stream data changes the state of the stream. By returning the stream, you allow for chaining stream operations in a single statement, as shown earlier .

As an example, consider how to output the representation of a Dateobject in MM-DD-YYYY format. The following inserter does the job:

ostream& operator<<(ostream& os, const Date& d) {

char fillc = os.fill('0');

os << setw(2) << d.getMonth() << '-'

<< setw(2) << d.getDay() << '-'

<< setw(4) << setfill(fillc) << d.getYear();

return os;

}

This function cannot be a member of the Dateclass, of course, because the left operand of the <<operator must be the output stream. The fill( )member function of ostreamchanges the padding character used when the width of an output field, determined by the manipulator setw( ), is greater than needed for the data. We use a ‘0’ character so that months before October will display with a leading zero, such as "09" for September. The fill( )function also returns the previous fill character (which defaults to a single space) so that we can restore it later with the manipulator setfill( ). We discuss manipulators in depth later in this chapter .

Extractors require a little more care because things sometimes go wrong with input data. The way to signal a stream error is to set the stream’s fail bit , as follows:

istream& operator>>(istream& is, Date& d) {

is >> d.month;

char dash;

is >> dash;

if (dash != '-')

is.setstate(ios::failbit);

is >> d.day;

is >> dash;

if (dash != '-')

is.setstate(ios::failbit);

is >> d.year;

return is;

}

When an error bit is set in a stream, all further streams operations are ignored until the stream is restored to a good state (explained shortly). That’s why the code above continues extracting even if ios::failbitgets set. This implementation is somewhat forgiving in that it allows white space between the numbers and dashes in a date string (because the >>operator skips white space by default when reading built-in types). The following are valid date strings for this extractor: .

"08-10-2003"

"8-10-2003"

"08 - 10 - 2003"

but these are not:

"A-10-2003" // No alpha characters allowed

"08%10/2003" // Only dashes allowed as a delimiter

We’ll discuss stream state in more depth in the section "Handling stream errors" later in this chapter .

Common usage

As the Dateextractor illustrated, you must be on guard for erroneous input. If the input produces an unexpected value, the process is skewed, and it’s difficult to recover. In addition, formatted input defaults to white space delimiters. Consider what happens when we collect the code fragments from earlier in this chapter into a single program: .

//: C04:Iosexamp.cpp

// Iostream examples

#include

using namespace std;

int main() {

int i;

cin >> i;

float f;

cin >> f;

char c;

cin >> c;

char buf[100];

cin >> buf;

cout << "i = " << i << endl;

cout << "f = " << f << endl;

cout << "c = " << c << endl;

cout << "buf = " << buf << endl;

cout << flush;

cout << hex << "0x" << i << endl;

} ///:~

and give it the following input: .

12 1.4 c this is a test

We expect the same output as if we gave it:

12

1.4

c

this is a test

but the output is, somewhat unexpectedly

i = 12

f = 1.4

c = c

buf = this

0xc

Notice that bufgot only the first word because the input routine looked for a space to delimit the input, which it saw after "this." In addition, if the continuous input string is longer than the storage allocated for buf, we overrun the buffer .

In practice, you’ll usually want to get input from interactive programs a line at a time as a sequence of characters, scan them, and then perform conversions once they’re safely in a buffer. This way you don’t have to worry about the input routine choking on unexpected data .

Another thing to consider is the whole concept of a command-line interface. This made sense in the past when the console was little more than a glass typewriter, but the world is rapidly changing to one in which the graphical user interface (GUI) dominates. What is the meaning of console I/O in such a world? It makes much more sense to ignore cinaltogether, other than for simple examples or tests, and take the following approaches: .

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Thinking In C++. Volume 2: Practical Programming»

Представляем Вашему вниманию похожие книги на «Thinking In C++. Volume 2: Practical Programming» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «Thinking In C++. Volume 2: Practical Programming»

Обсуждение, отзывы о книге «Thinking In C++. Volume 2: Practical Programming» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x