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

Since you don’t know when you’re writing the template which type of stream you have, you need a way to automatically convert character literals to the correct size for the stream. This is the job of the widen( ) member function. The expression widen('-'), for example, converts its argument to L’-’ (the literal syntax equivalent to the conversion wchar_t(‘-’)) if the stream is a wide stream and leaves it alone otherwise. There is also a narrow( ) function that converts to a char if needed.

We can use widen( ) to write a generic version of the nl manipulator we presented earlier in the chapter.

template

basic_ostream&

nl(basic_ostream& os) {

  return os << charT(os.widen('\n'));

}

<p>Locales</p>

Perhaps the most notable difference in typical numeric computer output from country to country is the punctuator used to separate the integer and fractional parts of a real number. In the United States, a period denotes a decimal point, but in much of the world, a comma is expected instead. It would be quite inconvenient to do all your own formatting for locale-dependent displays. Once again, creating an abstraction that handles these differences solves the problem.

That abstraction is the locale. All streams have an associated locale object that they use for guidance on how to display certain quantities for different cultural environments. A locale manages the categories of culture-dependent display rules, which are defined as follows:

CategoryEffect
collateallows comparing strings according to different, supported collating sequences
ctypeabstracts the character classification and conversion facilities found in
monetarysupports different displays of monetary quantities
numericsupports different display formats of real numbers, including radix (decimal point) and grouping (thousands) separators
timesupports various international formats for display of date and time
messagesscaffolding to implement context-dependent message catalogs (such as for error messages in different languages)

The following program illustrates basic locale behavior:

//: C04:Locale.cpp

//{-g++}

//{-bor}

//{-edg}

// Illustrates effects of locales

#include

#include

using namespace std;

int main() {

  locale def;

  cout << def.name() << endl;

  locale current = cout.getloc();

  cout << current.name() << endl;

  float val = 1234.56;

  cout << val << endl;

  // Change to French/France

  cout.imbue(locale("french"));

  current = cout.getloc();

  cout << current.name() << endl;

  cout << val << endl;

  cout << "Enter the literal 7890,12: ";

  cin.imbue(cout.getloc());

  cin >> val;

  cout << val << endl;

  cout.imbue(def);

  cout << val << endl;

} ///:~

Here’s the output:

C

C

1234.56

French_France.1252

1234,56

Enter the literal 7890,12: 7890,12

7890,12

7890.12

The default locale is the "C" locale, which is what C and C++ programmers have been used to all these years (basically, English language and American culture). All streams are initially "imbued" with the "C" locale. The imbue( ) member function changes the locale that a stream uses. Notice that the full ISO name for the "French" locale is displayed (that is, French used in France vs. French used in another country). This example shows that this locale uses a comma for a radix point in numeric display. We have to change cin to the same locale if we want to do input according to the rules of this locale.

Each locale category is divided into number of facets, which are classes encapsulating the functionality that pertains to that category. For example, the time category has the facets time_put and time_get, which contain functions for doing time and date input and output respectively. The monetary category has facets money_get, money_put, and moneypunct. (The latter facet determines the currency symbol.) The following program illustrates the moneypunct facet. (The time facet requires a sophisticated use of iterators which is beyond the scope of this chapter.)

//: C04:Facets.cpp

//{-bor}

//{-g++}

#include

#include

#include

using namespace std;

int main() {

  // Change to French/France

  locale loc("french");

  cout.imbue(loc);

  string currency =

    use_facet >(loc).curr_symbol();

  char point =

    use_facet >(loc).decimal_point();

  cout << "I made " << currency << 12.34 << " today!"

       << endl;

} ///:~

The output shows the French currency symbol and decimal separator:

I made Ç12,34 today!

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

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

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

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

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

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

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

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

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