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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

D(T << endl << f << endl;)

D(T.setf(ios::scientific, ios::floatfield);)

D(T << endl << f << endl;)

D(T.setf(ios::fixed, ios::floatfield);)

D(T << f << endl;)

D(T.width(10);)

T << s << endl;

D(T.width(40);)

T << s << endl;

D(T.setf(ios::left, ios::adjustfield);)

D(T.width(40);)

T << s << endl;

} ///:~

This example uses a trick to create a trace file so that you can monitor what’s happening. The macro D(a)uses the preprocessor "stringizing" to turn ainto a string to display. Then it reiterates aso the statement is executed. The macro sends all the information to a file called T, which is the trace file. The output is: .

int i = 47;

float f = 2300114.414159;

T.setf(ios::unitbuf);

T.setf(ios::showbase);

T.setf(ios::uppercase | ios::showpos);

T << i << endl;

+47

T.setf(ios::hex, ios::basefield);

T << i << endl;

0X2F

T.setf(ios::oct, ios::basefield);

T << i << endl;

057

T.unsetf(ios::showbase);

T.setf(ios::dec, ios::basefield);

T.setf(ios::left, ios::adjustfield);

T.fill('0');

T << "fill char: " << T.fill() << endl;

fill char: 0

T.width(10);

+470000000

T.setf(ios::right, ios::adjustfield);

T.width(10);

0000000+47

T.setf(ios::internal, ios::adjustfield);

T.width(10);

+000000047

T << i << endl;

+47

T.unsetf(ios::showpos);

T.setf(ios::showpoint);

T << "prec = " << T.precision() << endl;

prec = 6

T.setf(ios::scientific, ios::floatfield);

T << endl << f << endl;

2.300114E+06

T.unsetf(ios::uppercase);

T << endl << f << endl;

2.300114e+06

T.setf(ios::fixed, ios::floatfield);

T << f << endl;

2300114.500000

T.precision(20);

T << "prec = " << T.precision() << endl;

prec = 20

T << endl << f << endl;

2300114.50000000000000000000

T.setf(ios::scientific, ios::floatfield);

T << endl << f << endl;

2.30011450000000000000e+06

T.setf(ios::fixed, ios::floatfield);

T << f << endl;

2300114.50000000000000000000

T.width(10);

Is there any more?

T.width(40);

0000000000000000000000Is there any more?

T.setf(ios::left, ios::adjustfield);

T.width(40);

Is there any more?0000000000000000000000

Studying this output should clarify your understanding of the iostream formatting member functions .

Manipulators

As you can see from the previous program, calling the member functions for stream formatting operations can get a bit tedious. To make things easier to read and write, a set of manipulators is supplied to duplicate the actions provided by the member functions. Manipulators are a convenience because you can insert them for their effect within a containing expression; you don’t have to create a separate function-call statement .

Manipulators change the state of the stream instead of (or in addition to) processing data. When you insert endlin an output expression, for example, it not only inserts a newline character, but it also flushes the stream (that is, puts out all pending characters that have been stored in the internal stream buffer but not yet output). You can also just flush a stream like this: .

cout << flush;

which causes a call to the flush( )member function, as in

cout.flush();

as a side effect (nothing is inserted into the stream). Additional basic manipulators will change the number base to oct(octal), dec(decimal) or hex(hexadecimal): .

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

In this case, numeric output will continue in hexadecimal mode until you change it by inserting either decor octin the output stream.

There’s also a manipulator for extraction that "eats" white space: .

cin >> ws;

Manipulators with no arguments are provided in . These include dec, oct, and hex, which perform the same action as, respectively, setf(ios::dec, ios::basefield), setf(ios::oct, ios::basefield), and setf(ios::hex, ios::basefield), albeit more succinctly. The header also includes ws, endl, and flushand the additional set shown here: .

Manipulator Effect
showbase noshowbase Indicate the numeric base ( dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler.
showpos noshowpos Show plus sign (+) for positive values.
uppercase nouppercase Display uppercase A-F for hexadecimal values, and display E for scientific values.
showpoint noshowpoint Show decimal point and trailing zeros for floating-point values.
skipws noskipws Skip white space on input.
left right internal Left-align, pad on right. Right-align, pad on left. Fill between leading sign or base indicator and value.
scientific fixed Indicates the display preference for floating-point output (scientific notation vs. fixed-point decimal).

Manipulators with arguments

There are six standard manipulators, such as setw( ), that take arguments. These are defined in the header file < iomanip>, and are summarized in the following table.

Manipulator effect
setiosflags (fmtflags n) Equivalent to a call to setf(n). The setting remains in effect until the next change, such as ios::setf( ).
resetiosflags(fmtflags n) Clears only the format flags specified by n. The setting remains in effect until the next change, such as ios::unsetf( ).
setbase(base n) Changes base to n, where nis 10, 8, or 16. (Anything else results in 0.) If nis zero, output is base 10, but input uses the C conventions: 10 is 10, 010 is 8, and 0xf is 15. You might as well use dec, oct, and hexfor output.
setfill(char n) Changes the fill character to n, such as ios::fill( ).
setprecision(int n) Changes the precision to n, such as ios::precision( ).
setw(int n) Changes the field width to n, such as ios::width( ).

If you’re doing a lot of formatting, you can see how using manipulators instead of calling stream member functions can clean up your code. As an example, here’s the program from the previous section rewritten to use the manipulators. (The D( )macro is removed to make it easier to read.) .

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

Интервал:

Закладка:

Сделать

Похожие книги на «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