Читаем Thinking In C++. Volume 2: Practical Programming полностью

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.

<p>Manipulators</p>

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 endl in 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 dec or oct in 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 flush and the additional set shown here:.

ManipulatorEffect
showbase noshowbaseIndicate the numeric base (dec, oct, or hex) when printing an integral value. The format used can be read by the C++ compiler.
showpos noshowposShow plus sign (+) for positive values.
uppercase nouppercaseDisplay uppercase A-F for hexadecimal values, and display E for scientific values.
showpoint noshowpointShow decimal point and trailing zeros for floating-point values.
skipws noskipwsSkip white space on input.
left right internalLeft-align, pad on right. Right-align, pad on left. Fill between leading sign or base indicator and value.
scientific fixedIndicates the display preference for floating-point output (scientific notation vs. fixed-point decimal).
<p>Manipulators with arguments</p>

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.

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

Похожие книги

3ds Max 2008
3ds Max 2008

Одни уверены, что нет лучшего способа обучения 3ds Мах, чем прочитать хорошую книгу. Другие склоняются к тому, что эффективнее учиться у преподавателя, который показывает, что и как нужно делать. Данное издание объединяет оба подхода. Его цель – сделать освоение 3ds Мах 2008 максимально быстрым и результативным. Часто после изучения книги у читателя возникают вопросы, почему не получился тот или иной пример. Видеокурс – это гарантия, что такие вопросы не возникнут: ведь автор не только рассказывает, но и показывает, как нужно работать в 3ds Мах.В отличие от большинства интерактивных курсов, где работа в 3ds Мах иллюстрируется на кубиках-шариках, данный видеокурс полностью практический. Все приемы работы с инструментами 3ds Мах 2008 показаны на конкретных примерах, благодаря чему после просмотра курса читатель сможет самостоятельно выполнять даже сложные проекты.

Владимир Антонович Верстак , Владимир Верстак

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