Читаем C++ Primer Plus полностью

Listing 17.9 illustrates further examples of using setf() with two arguments.

Note

The program in Listing 17.9 uses a math function, and some C++ systems don’t automatically search the math library. For example, some Unix systems require that you use the following:

$ CC setf2.C -lm

The -lm option instructs the linker to search the math library. Similarly, some Linux systems using g++ require the same flag.

Listing 17.9. setf2.cpp

// setf2.cpp -- using setf() with 2 arguments to control formatting

#include

#include

int main()

{

    using namespace std;

   // use left justification, show the plus sign, show trailing

    // zeros, with a precision of 3

    cout.setf(ios_base::left, ios_base::adjustfield);

    cout.setf(ios_base::showpos);

    cout.setf(ios_base::showpoint);

    cout.precision(3);

    // use e-notation and save old format setting

    ios_base::fmtflags old = cout.setf(ios_base::scientific,

        ios_base::floatfield);

    cout << "Left Justification:\n";

    long n;

    for (n = 1; n <= 41; n+= 10)

    {

        cout.width(4);

        cout << n << "|";

        cout.width(12);

        cout << sqrt(double(n)) << "|\n";

    }

    // change to internal justification

    cout.setf(ios_base::internal, ios_base::adjustfield);

    // restore default floating-point display style

    cout.setf(old, ios_base::floatfield);

    cout << "Internal Justification:\n";

    for (n = 1; n <= 41; n+= 10)

    {

        cout.width(4);

        cout << n << "|";

        cout.width(12);

        cout << sqrt(double(n)) << "|\n";

    }

    // use right justification, fixed notation

    cout.setf(ios_base::right, ios_base::adjustfield);

    cout.setf(ios_base::fixed, ios_base::floatfield);

    cout << "Right Justification:\n";

    for (n = 1; n <= 41; n+= 10)

    {

        cout.width(4);

        cout << n << "|";

        cout.width(12);

        cout << sqrt(double(n)) << "|\n";

    }

    return 0;

}

Here is the output of the program in Listing 17.9:

Left Justification:

+1  |+1.000e+00  |

+11 |+3.317e+00  |

+21 |+4.583e+00  |

+31 |+5.568e+00  |

+41 |+6.403e+00  |

Internal Justification:

+  1|+       1.00|

+ 11|+       3.32|

+ 21|+       4.58|

+ 31|+       5.57|

+ 41|+       6.40|

Right Justification:

  +1|      +1.000|

 +11|      +3.317|

 +21|      +4.583|

 +31|      +5.568|

 +41|      +6.403|

Note how a precision of 3 causes the default floating-point display (used for internal justification in this program) to display a total of three digits, while the fixed and scientific modes display three digits to the right of the decimal. (The number of digits displayed in the exponent for e-notation depends on the implementation.)

The effects of calling setf() can be undone with unsetf(), which has the following prototype:

void unsetf(fmtflags mask);

Here mask is a bit pattern. All bits set to 1 in mask cause the corresponding bits to be unset. That is, setf() sets bits to 1, and unsetf() sets bits back to 0. Here’s an example:

cout.setf(ios_base::showpoint);       // show trailing decimal point

cout.unsetf(ios_base::boolshowpoint); // don't show trailing decimal point

cout.setf(ios_base::boolalpha);       // display true, false

cout.unsetf(ios_base::boolalpha);     // display 1, 0

You may have noticed that there is no special flag to indicate the default mode for displaying floating-point numbers. Here’s how the system works. Fixed notation is used if the fixed bit, and only the fixed bit is set. Scientific notation is used if the scientific bit and only the scientific bit is set. Any other combination, such as no bits set or both bits set, results in the default mode being used. So one way to invoke the default mode is this:

cout.setf(0, ios_base::floatfield);  // go to default mode

The second argument turns both bits off, and the first argument doesn’t set any bits. A shorter way to accomplish the same end is to use unsetf() with ios_base::floatfield:

cout.unsetf(ios_base::floatfield);   // go to default mode

If you knew for certain that cout were in the fixed state, you could use ios_base::fixed as an argument to unsetf(), but using ios_base::floatfield works, regardless of the current state of cout, so it’s a better choice.

Standard Manipulators

Using setf() is not the most user-friendly approach to formatting, so C++ offers several manipulators to invoke setf() for you, automatically supplying the right arguments. You’ve already seen dec, hex, and oct. These manipulators, most of which are not available to older C++ implementations, work like hex. For example, the following statement turns on left-justification and the fixed decimal point option:

cout << left << fixed;

Table 17.3 lists these along with several other manipulatrs.

Table 17.3. Some Standard Manipulators

Tip

If your system supports these manipulators, take advantage of them; if it doesn’t, you still have the option of using setf().

The iomanip Header File

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

Все книги серии Developer's Library

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

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

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

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

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

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

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

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

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

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