Читаем Linux программирование в примерах полностью

    0 Количество и int_curr_symbol окружены скобками.

    1 Строка знака до количества и int_curr_symbol.

    2 Строка знака после количества и int_curr_symbol.

    3 Строка знака непосредственно до int_curr_symbol.

    4 Строка знака непосредственно после int_curr_symbol. */

 char int_p_sign_posn;

 char int_n_sign_posn;

};

Комментарии показывают довольно ясно, что происходит. Давайте посмотрим на несколько первых полей struct lconv:

decimal_point

Используемый символ разделителя десятичной дроби. В Соединенных Штатах и других англоязычных странах это точка, но во многих странах используется запятая.

thousands_sep

Символ, используемый для разделения каждых 3 цифр значения.

grouping

Массив однобайтных целых значений. Каждый элемент указывает, сколько цифр в группе. Как сказано в комментарии, CHAR_MAX означает, что дальше группировка не используется, а 0 означает повторное использование последнего элемента (Далее в главе мы покажем пример кода.)

int_curr_symbol

Это международный символ для местной валюты. Например, 'USD' для доллара США.

currency_symbol

Локальный символ для местной валюты. Например, $ для доллара США.

mon_decimal_point, mon_thousands_sep, mon_grouping

Соответствуют предыдущим полям, предоставляя те же сведения, но для денежных сумм.

Большая часть оставшихся значений не имеет значения для повседневного программирования. Следующая программа, ch13-lconv.c, выводит некоторые из этих значений, чтобы дать вам представление, для какого рода сведений они используются:

/* ch13-lconv.c --- показывает некоторые компоненты struct lconv */

#include

#include

#include

int main(void) {

 struct lconv l;

 int i;

 setlocale(LC_ALL, "");

 l = *localeconv();

 printf("decimal_point = [%s]\n", l.decimal_point);

 printf("thousands_sep = [%s]\n", l.thousands_sep);

 for (i = 0; l.grouping[i] != 0 && l.grouping[i] != CHAR_MAX; i++)

  printf("grouping[%d] = [%dj\n", i, l.grouping[i]);

 printf("int_curr_symbol = [%s]\n", l.int_curr_symbol);

 printf("currency_symbol = f%s]\n", l.currency_symbol);

 printf("mon_decimal_point = f%s]\n", l.mon_decimal_point);

 printf("mon_thousands_sep = [%s]\n", l.mon_thousands_sep);

 printf("positive_sign = [%s]\n", l.positive_sign);

 printf("negative_sign = [%s]\n", l.negative_sign);

}

Неудивительно, при запуске в различных локалях мы получаем различные результаты.

$ LC_ALL=en_US ch13-lconv /* Результаты для Соединенных Штатов */

decimal_point = [.]

thousands_sep = [,]

grouping[0] = [3]

grouping[1] = [3]

int_curr_symbol = [USD ]

currency_symbol = [$]

mon_decimal_point = [.]

mon_thousands_sep = [,]

positive_sign = []

negative_sign = [-]

$ LC_ALL=it_IT ch13-lconv /* Результаты для Италии */

decimal_point = [.]

thousands_sep = []

int_curr_symbol = []

currency_symbol = []

mon_decimal_point = []

mon_thousands_sep = []

positive_sign = []

negative_sign = []

Обратите внимание, что значение int_curr_symbol в локали "en_US" включает завершающий символ пробела, который служит для отделения символа от последующего денежного значения.

<p>13.2.5. Высокоуровневое числовое и денежное форматирование: <code>strfmon()</code> и <code>printf()</code></p>

После рассмотрения всех полей struct lconv вы можете поинтересоваться: «Нужно ли мне на самом деле выяснять, как использовать все эти сведения, просто для форматирования денежного значения?» К счастью, ответом является «нет».[140] Функция strfmon() делает за вас всю работу:

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

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

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

Стивен Прата

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