Читаем 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.

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

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

1С: Бухгалтерия 8 с нуля
1С: Бухгалтерия 8 с нуля

Книга содержит полное описание приемов и методов работы с программой 1С:Бухгалтерия 8. Рассматривается автоматизация всех основных участков бухгалтерии: учет наличных и безналичных денежных средств, основных средств и НМА, прихода и расхода товарно-материальных ценностей, зарплаты, производства. Описано, как вводить исходные данные, заполнять справочники и каталоги, работать с первичными документами, проводить их по учету, формировать разнообразные отчеты, выводить данные на печать, настраивать программу и использовать ее сервисные функции. Каждый урок содержит подробное описание рассматриваемой темы с детальным разбором и иллюстрированием всех этапов.Для широкого круга пользователей.

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

Программирование, программы, базы данных / Программное обеспечение / Бухучет и аудит / Финансы и бизнес / Книги по IT / Словари и Энциклопедии
1С: Управление торговлей 8.2
1С: Управление торговлей 8.2

Современные торговые предприятия предлагают своим клиентам широчайший ассортимент товаров, который исчисляется тысячами и десятками тысяч наименований. Причем многие позиции могут реализовываться на разных условиях: предоплата, отсрочка платежи, скидка, наценка, объем партии, и т.д. Клиенты зачастую делятся на категории – VIP-клиент, обычный клиент, постоянный клиент, мелкооптовый клиент, и т.д. Товарные позиции могут комплектоваться и разукомплектовываться, многие товары подлежат обязательной сертификации и гигиеническим исследованиям, некондиционные позиции необходимо списывать, на складах периодически должна проводиться инвентаризация, каждая компания должна иметь свою маркетинговую политику и т.д., вообщем – современное торговое предприятие представляет живой организм, находящийся в постоянном движении.Очевидно, что вся эта кипучая деятельность требует автоматизации. Для решения этой задачи существуют специальные программные средства, и в этой книге мы познакомим вам с самым популярным продуктом, предназначенным для автоматизации деятельности торгового предприятия – «1С Управление торговлей», которое реализовано на новейшей технологической платформе версии 1С 8.2.

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

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