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

Functioneffect
int ios::width( )Returns the current width. (Default is 0.) Used for both insertion and extraction.
int ios::width(int n)Sets the width, returns the previous width.
int ios::fill( )Returns the current fill character. (Default is space.)
int ios::fill(int n)Sets the fill character, returns the previous fill character.
int ios::precision( )Returns current floating-point precision. (Default is 6.)
int ios::precision(int n)Sets floating-point precision, returns previous precision. See ios::floatfield table for the meaning of "precision."

The fill and precision values are fairly straightforward, but width requires some explanation. When the width is zero, inserting a value produces the minimum number of characters necessary to represent that value. A positive width means that inserting a value will produce at least as many characters as the width; if the value has fewer than width characters, the fill character is used to pad the field. However, the value will never be truncated, so if you try to print 123 with a width of two, you’ll still get 123. The field width specifies a minimum number of characters; there’s no way to specify a maximum number.

The width is also distinctly different because it’s reset to zero by each inserter or extractor that could be influenced by its value. It’s really not a state variable, but rather an implicit argument to the inserters and extractors. If you want a constant width, call width( ) after each insertion or extraction.

<p>An exhaustive example</p>

To make sure you know how to call all the functions previously discussed, here’s an example that calls them all:.

//: C04:Format.cpp

// Formatting Functions

#include

#include

#include "../require.h"

using namespace std;

#define D(A) T << #A << endl; A

int main() {

  ofstream T("format.out");

  assure(T);

  D(int i = 47;)

  D(float f = 2300114.414159;)

  const char* s = "Is there any more?";

  D(T.setf(ios::unitbuf);)

  D(T.setf(ios::showbase);)

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

  D(T << i << endl;) // Default is dec

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

  D(T << i << endl;)

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

  D(T << i << endl;)

  D(T.unsetf(ios::showbase);)

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

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

  D(T.fill('0');)

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

  D(T.width(10);)

  T << i << endl;

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

  D(T.width(10);)

  T << i << endl;

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

  D(T.width(10);)

  T << i << endl;

  D(T << i << endl;) // Without width(10)

  D(T.unsetf(ios::showpos);)

  D(T.setf(ios::showpoint);)

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

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

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

  D(T.unsetf(ios::uppercase);)

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

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

  D(T << f << endl;)

  D(T.precision(20);)

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

  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 a into a string to display. Then it reiterates a so 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

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

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

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

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

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

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

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

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

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