The <locale>
header declares templates and functions for internationalization and localization. It supports conversion between narrow and wide character sets, character classification and collation, formatting and parsing numbers, currency, dates, and times, and retrieving messages.
A locale is an embodiment of a set of cultural conventions, including information about the native character set, how dates are formatted, which symbol to use for currency, and so on. Each of these attributes is called a facet, where facets are grouped into categories.
The categories are fixed and defined by the standard (see Table 13-20, under locale::category
in this section, for a complete list), and each category has several predefined facets. For example, one of the facets in the time category is time_get<char,
InputIter>
, which specifies rules for parsing a time string. You can define additional facets; see the description of the locale::facet
class in this section for details.
Many of the facets come in two flavors: plain and named. The plain versions implement default behavior, and the named versions implement the behavior for a named locale. (See the locale
class, later in this section, for a discussion of locale names.)
When a program starts, the global locale is initialized to the "C"
locale, and the standard I/O streams are imbued with this locale. A program can change the locale at any time; see the locale
class in this section for details.
The C++ <locale>
header provides more functionality than the C <clocale>
and <cctype>
headers, especially the ability to extend a locale with your own facets. It is also more complicated, and adds overhead.
Facet for mapping one character set to another
template <typename internT,typename externT,typename stateT> class codecvt : public locale::facet, public codecvt_base { public: typedef internT intern_type; typedef externT extern_type; typedef stateT state_type; explicit codecvt(size_t refs = 0); result out(stateT& state, const internT* from, const internT* from_end, const internT*& from_next, externT* to, externT* to_limit, externT*& to_next) const; result unshift(stateT& state, externT* to, externT* to_limit, externT*& to_next) const; result in(stateT& state, const externT* from, const externT* from_end, const externT*& from_next, internT* to, internT* to_limit, internT*& to_next) const; int encoding() const throw(); bool always_noconv() const throw(); int length(stateT&, const externT* from, const externT* end, size_t max) const; int max_length() const throw(); static locale::id id; protected: virtual ~codecvt(); virtual result do_out(stateT& state, const internT* from, const internT* from_end, const internT*& from_next, externT* to, externT* to_limit, externT*& to_next) const; virtual result do_in(stateT& state, const externT* from, const externT* from_end, const externT*& from_next, internT* to, internT* to_limit, internT*& to_next) const; virtual result do_unshift(stateT& state, externT* to, externT* to_limit, externT*& to_next) const; virtual int do_encoding() const throw(); virtual bool do_always_noconv() const throw(); virtual int do_length(stateT&, const externT* from, const externT* end, size_t max) const; virtual int do_max_length() const throw(); };
The codecvt
template converts characters from one character encoding to another. The most common use is to convert multibyte characters to and from wide characters.
The following template speciailizations are required by the standard:
codecvt<wchar_t,
char,
mbstate_t>
converts multibyte narrow characters to wide characters;codecvt<char,
char,
mbstate_t>
is a no-op, "converting" characters to themselves.As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as in
and out
, which call do_in
and do_out
. The descriptions below are for the virtual functions because they do the real work.
virtual
bool
do_always_noconv
()
const
throw()
do_always_noconv
function returns true if the codecvt
object does not actually perform any conversions, that is, in and out are no-ops. For example, the specialization codecvt<char,char,mbstate_t>
returns true
from do_always_noconv
.virtual
int
do_encoding
()
const
throw()
do_encoding
function returns the number of externT
characters needed to represent a single internT
character. If this number is not a fixed constant, the return value is 0. The return value is -1 if externT
character sequences are not state-dependent.virtual
result
do_in
(stateT&
state,
const
externT*
from,
const externT*
from_end,
const
externT*&
from_next,
internT*
to,
internT*
to_limit,
internT*&
to_next)
const
do_in
function converts externT
characters to internT
characters. The characters in the range
[from
, from_end
) are converted and stored in the array starting at to
. The number of characters converted is the minimum of from_end
- from
and to_limit
- to
.from_next
parameter is set to point to the value in [from
, from_end
) where the conversion stopped, and to_next
points to the value in [to
, to_limit
) where the conversion stopped. If no conversion was performed, from_next
is the same as from
, and to_next
is equal to to
.result
, as described in Table 13-18, under codecvt_base
class, later in this section.virtual
int
do_length
(stateT&,
const
externT*
from,
const
externT*
from_end,
size_t
max)
const
do_length
function returns the number of externT
characters in tha range [from
, from_end
) that are used to convert to internT
characters. At most max
internT
characters are converted.virtual
int
do_max_length
()
const
throw()
do_max_length
function returns the maximum number of externT
characters needed to represent a single internT
character, that is, the maximum value that do_length
can return when max
is 1.virtual
result
do_out
(stateT&
state,
const
internT*
from,
const
internT*
from_end,
const
internT*&
from_next,
externT*
to,
externT*
to_limit,
externT*&
to_next)
const
do_out
function converts internT
characters to externT
characters. The characters in the range
[from
, from_end
) are converted and stored in the array starting at to
. The number of characters converted is the minimum of from_end
- from
and to_limit
- to
.from_next
parameter is set to point to the value in [from
, from_end
) where the conversion stopped, and to_next
points to the value in [to
, to_limit
) where the conversion stopped. If no conversion was performed, from_next
is the same as from
, and to_next
is equal to to
.result
, as described in Table 13-18, under codecvt_base
class, later in this section.virtual
result
do_unshift
(stateT&
state,
externT*
to,
externT*
to_limit,
externT*&
to_next)
const
do_unshift
function stores characters in the array starting at to to
end any state shift sequences, as given by state
. Up to to_limit
- to
characters are written, and to_next
is set to point to one past the last character written into to
.result
, as described in Table 13-18, under codecvt_base
class, later in this section.codecvt_base class, codecvt_byname class template, locale::facet class
Base class for the codecvt template
class codecvt_base { public: enum result { ok, partial, error, noconv }; };
The codecvt_base
class is the base class for the codecvt
and codecvt_byname
class templates. It declares the result
type, which is the type returned by the do_in
and do_out
conversion functions. Table 13-18 lists the literals of the result
enumerated type.
Literal | Description |
---|---|
error |
Error in conversion, e.g., invalid state or multibyte character sequence |
noconv |
No conversion (or unshift terminated) needed |
ok |
Conversion finished successfully |
partial |
Not all source characters converted, or or unshift sequence is incomplete |
codecvt class template, codecvt_byname class template
Facet for mapping one character set to another
template<typename internT, typename externT, typename stateT> class codecvt_byname : public codecvt<internT, externT, stateT> { public: explicit codecvt_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in codecvt };
The codecvt_byname
class template converts characters from one character encoding to another, using the rules of a named locale. The codecvt_byname<char>
and codecvt_byname<wchar_t>
instantiations are standard.
codecvt class template, locale::facet class
Facet for comparing strings in collation order
template <typename charT> class collate : public locale::facet { public: typedef charT char_type; typedef basic_string<charT> string_type; explicit collate(size_t refs = 0); int compare(const charT* low1, const charT* high1, const charT* low2, const charT* high2) const; string_type transform(const charT* low, const charT* high) const; long hash(const charT* low, const charT* high) const; static locale::id id; protected: virtual ~collate(); virtual int do_compare(const charT* low1, const charT* high1, const charT* low2, const charT* high2) const; virtual string_type do_transform (const charT* low, const charT* high) const; virtual long do_hash (const charT* low, const charT* high) const; };
The collate
class template is a facet used to compare strings. In some locales, the collation order of characters is not the same as the numerical order of their encodings, or some characters might be logically equivalent even if they have different encodings.
You can use a locale
object as a comparator for algorithms that need a comparison function; the locale's operator()
uses the collate
facet to perform the comparison.
The standard mandates the collate<char>
and collate<wchar_t>
instantiations, which perform lexicographical (element-wise) comparison. (See lexicographical_compare
in <algorithm>
, earlier in this chapter.)
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as compare
, which calls do_compare
. The descriptions below are for the virtual functions because they do the real work.
virtual
int
do_compare
(const
charT*
low1,
const
charT*
high1,
const
charT*
low2,
const
charT*
high2)
const
do_compare
function compares the character sequences [low1
, high1
) with the character sequence [low2
, high2
). The return value is one of the following:virtual
long
do_hash
(const
charT*
low,
const
charT*
high)
const
do_hash
function returns a hash value for the character sequence [low
, high
). If do_compare
returns 0 for two character sequences, do_hash
returns the same value for the two sequences. The reverse is not necessarily the case.virtual
string_type
do_transform
(const
charT*
low,
const
charT*
high)
const
do_transform
function transforms the character sequence [low
, high
) into a string that can be compared simply with another transformed string to obtain the same result as calling do_compare
on the original character sequences. The do_transform
function is useful if a program needs to collate the same character sequence many times.collate_byname class template, locale class, locale::facet class
Facet for comparing strings in collation order
template <typename charT> class collate_byname : public collate<charT> { public: typedef basic_string<charT> string_type; explicit collate_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in collate };
The collate_byname
class template compares strings using a named locale's collation order. The collate_byname<char>
and collate_byname<wchar_t>
instantiations are standard.
collate class template, locale::facet class
Facet for classifying characters
class ctype : public locale::facet, public ctype_base { public: typedef charT char_type; explicit ctype(size_t refs = 0); bool is(mask m, charT c) const; const charT* is(const charT* low, const charT* high, mask* vec) const; const charT* scan_is(mask m, const charT* low, const charT* high) const; const charT* scan_not(mask m, const charT* low, const charT* high) const; charT toupper(charT c) const; const charT* toupper(charT* low, const charT* high) const; charT tolower(charT c) const; const charT* tolower(charT* low, const charT* high) const; charT widen(char c) const; const char* widen(const char* low, const char* high, charT* to) const; char narrow(charT c, char dfault) const; const charT* narrow(const charT* low, const charT*, char dfault, char* to) const; static locale::id id; protected: virtual ~ctype(); virtual bool do_is(mask m, charT c) const; virtual const charT* do_is(const charT* low, const charT* high, mask* vec) const; virtual const charT* do_scan_is(mask m, const charT* low, const charT* high) const; virtual const charT* do_scan_not(mask m, const charT* low, const charT* high) const; virtual charT do_toupper(charT) const; virtual const charT* do_toupper(charT* low, const charT* high) const; virtual charT do_tolower(charT) const; virtual const charT* do_tolower(charT* low, const charT* high) const; virtual charT do_widen(char) const; virtual const char* do_widen(const char* low, const char* high, charT* dest) const; virtual char do_narrow(charT, char dfault) const; virtual const charT* do_narrow(const charT* low, const charT* high, char dfault, char* dest) const; };
The ctype
class template is a facet for classifying characters, using the <cctype>
header.
The ctype<char>
specialization is described in its own section, later in this chapter. The standard also mandates the ctype<wchar_t>
instantiation. Both instantiations depend on the implementation's native character set.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as narrow
, which calls do_narrow
. The descriptions below are for the virtual functions because they do the real work.
virtual
bool
do_is
(mask m, charT c) const
virtual
const
charT*
do_is
(const
charT*
low,
const
charT*
high,
mask*
vec)
const
do_is
function classifies a single character c
or a sequence of characters [low
, high
). The first form returns the classification mask. The second form determines the mask for each character in the range and stores the mask
values in the vec
array (which must be large enough to hold high
- low
masks), returning high
. See Table 13-19, under the ctype_base
class, later in this section, for a description of the mask
type.virtual
char
do_narrow
(charT c, char dfault) const
virtual
const
charT*
do_narrow
(const charT* low,
const charT* high, char dfault, char* dest)
const
do_narrow
function converts a character c
or a sequence of characters [low
, high
) to narrow characters of type char
. The first form returns the narrow character, and the second form stores the characters in the array dest
(which must be large enough to hold high
- low
characters), returning high. If a charT
source characters cannot be converted to a narrow character, the value of dfault
is returned or stored in dest
.virtual
const
charT*
do_scan_is
(mask m,
const charT* low, const charT* high) const
do_scan_is
function searches the sequence of characters [low
, high
) for the first character that matches m
, that is, for which do_is(m,
c)
is true. The return value is a pointer to to the first matching character, or high
if no characters match m
.virtual
const
charT*
do_scan_not
(mask m,
const charT* low, const charT* high) const
do_scan_is
function searches the sequence of characters [low
, high
) for the first character that does not match m
, that is, for which do_is(m,
c)
is false. The return value is a pointer to to the first matching character, or high
if every character matches m
.virtual
charT
do_tolower
(charT
c) const
virtual
const
charT*
do_tolower
(charT* low,
const charT* high) const
do_tolower
function converts a character c
or a sequence of characters [low
, high
) to lowercase. The first form returns the lowercase version of c
, or it returns c
if c
does not have a lowercase counterpart.low
, high
) is replaced by its lowercase counterpart; if a character cannot be converted to lowercase, it is not touched. The function returns high
.virtual
charT
do_toupper
(charT
c)
const
virtual
const
charT*
do_toupper
(charT*
low,
const charT* high) const
do_toupper
function converts a character c
or a sequence of characters [low
, high
) to uppercase. The first form returns the uppercase version of c
, or it returns c
if c
does not have a uppercase counterpart.low
, high
) is replaced by its uppercase counterpart; if a character cannot be converted to uppercase, it is not touched. The function returns high
.virtual
charT
do_widen
(char c) const
virtual
const
char*
do_widen
(const char* low,
const char* high, charT* dest) const
do_widen
function converts a narrow character c
or a sequence of narrow characters [low
, high
) to characters of type charT
. The first form returns the new character, and the second form stores the characters in the array dest
(which must be large enough to hold high
- low
characters), returning high.ctype_base class, ctype_byname class template, locale::facet class
Facet for classifying narrow characters
template <> class ctype<char> : public locale::facet, public ctype_base { ... public: explicit ctype(const mask* tab = 0, bool del = false, size_t refs = 0); static const size_t table_size = ...; protected: virtual ~ctype(); const mask* table() const throw(); static const mask* classic_table() throw(); };
The ctype<>
class template is specialized for type char
(but not signed
char
or unsigned
char
) so the member functions can be implemented as inline functions. The standard requires the implementation to have protected members table
and classic_table
. Each of these functions returns an array of mask values, indexed by characters cast to unsigned
char
. Following are the key member functions:
explicit
ctype
(const mask* tab = 0, bool del = false,
size_t refs = 0)
table()
pointer with tab. If tab is a null pointer, table()
is set to classic_table().
If tab
is not null, and del
is true, the destructor will delete the table. The refs
parameter is passed to the base class, as with any facet.static const mask*
classic_table
() throw()
classic_table
function returns a table that corresponds to the "C"
locale.ctype class template, locale::facet class, <cctype>
Base class for ctype facet
class ctype_base { public: enum mask { space, print, cntrl, upper, lower, alpha, digit, punct, xdigit, alnum=alpha|digit, graph=alnum|punct }; };
The ctype_base
class is the base class for the ctype
and ctype_byname
class templates. It declares the mask
enumerated type, which is used for classifying characters. Table 13-19 describes the mask
literals and their definitions for the classic "C"
locale.
Literal | Description | "C" locale |
---|---|---|
alpha |
Alphabetic (a letter) | lower or upper |
alnum |
Alphanumeric (letter or digit) | alpha or digit |
cntrl |
Control (non-printable) | not print |
digit |
'0' ...'9' in all locales |
|
graph |
Character that occupies graphical space | alnum or punct |
lower |
Lowercase letter | 'a' ... 'z' |
print |
Printable character (alphanumeric, punctuation, space, etc.) | (depends on character set; in ASCII: ' ' ... '\x7e' ) |
space |
White space | ' ' , '\f' , '\n' , '\r' , '\t' , '\v' |
upper |
Uppercase letter | 'a' ... 'z' |
xdigit |
Hexadecimal digit ('0' ...'9' , 'a' ...'f' , 'A' ...'F' ) in all locales |
ctype class template, ctype_byname class template
Facet for classifying characters
template <typename charT> class ctype_byname : public ctype<charT> { public: typedef ctype<charT>::mask mask; explicit ctype_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in ctype };
The ctype_byname
class template is a facet for classifying characters, using a named locale. The ctype_byname<char>
and ctype_byname<wchar_t>
instantiations are standard.
ctype class template, ctype_byname<char> class
Facet for classifying narrow characters
template <> class ctype_byname<char> : public ctype<char> { public: explicit ctype_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in ctype<char> };
The ctype_byname<char>
class specializes the ctype_byname
template for type char
. (No specialization exists for signed
char
or unsigned
char
.) It derives from ctype<char>
, and so inherits the table-driven implementation.
ctype<char> class, ctype_byname class template
Test for existence of a facet in a locale
template <typename Facet> bool has_facet(const locale& loc) throw();
The has_facet
function determines whether the locale's loc
supports the facet Facet
. It returns true
if the facet is supported or false
if not. Call has_facet
to determine whether a locale supports a user-defined facet. (Every locale must support the standard facets that are described in this section.) Example 13-27 shows an example of using has_facet
.
Example 13-27: Testing whether a locale supports a facet,
// The units facet is defined under the locale::facet // class, later in this section. using std::locale; if (std::has_facet<units>(locale()) { // Get a reference to the units facet of the locale. const units& u = std::use_facet<units>(locale()); // Construct a value of 42cm. units::value_t len = u.make(42, units::cm); // Print the length (42cm) in the locale's preferred units. u.length_put(std::cout, len); }
locale class, use_facet function template
Determine whether a character is alphanumeric in a locale
template <typename charT> bool isalnum(charT c, const locale& loc);
The isalnum
function determines whether the character c
is an alphanumeric character in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::alnum, c)
ctype_base class, ctype class template, isalpha function template, isdigit function template
Determine whether a character is a letter in a locale
template <typename charT> bool isalpha(charT c, const locale& loc);
The isalpha
function determines whether the character c
is a letter in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::alpha, c)
ctype_base class, ctype class template, isalnum function template, islower function template, isupper function template
Determine whether a character is a control character in a locale
template <typename charT> bool iscntrl(charT c, const locale& loc);
The iscntrl
function determines whether the character c
is a control character in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::cntrl, c)
ctype_base class, ctype class template, isprint function template
Determine whether a character is a digit in a locale
template <typename charT> bool isdigit(charT c, const locale& loc);
The isdigit
function determines whether the character c
is a digit in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::digit, c)
ctype_base class, ctype class template, isalnum function template, isxdigit function template
Determine whether a character is graphical in a locale
template <typename charT> bool isgraph(charT c, const locale& loc);
The isgraph
function determines whether the character c
is graphical (alphanumeric or punctuation) in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::graph, c)
ctype_base class, ctype class template, isalnum function template, isprint function template, ispunct function template
Determine whether a character is lowercase in a locale
template <typename charT> bool islower(charT c, const locale& loc);
The islower
function determines whether the character c
is a lowercase letter in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::lower, c)
ctype_base class, ctype class template, isalpha function template, isupper function template
Determine whether a character is printable in a locale
template <typename charT> bool isprint(charT c, const locale& loc);
The isprint
function determines whether the character c
is printable in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::print, c)
ctype_base class, ctype class template, iscntrl function template, isgraph function template, isspace function template
Determine whether a character is punctuation in a locale
template <typename charT> bool ispunct(charT c, const locale& loc);
The ispunct
function determines whether the character c
is punctuation in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::punct, c)
ctype_base class, ctype class template, isgraph function template
Determine whether a character is white space in a locale
template <typename charT> bool isspace(charT c, const locale& loc);
The isspace
function determines whether the character c
is white space in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::space, c)
ctype_base class, ctype class template, isgraph function template, isprint function template
Determine whether a character is uppercase in a locale
template <typename charT> bool isupper(charT c, const locale& loc);
The isupper
function determines whether the character c
is an uppercase letter in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::upper, c)
ctype_base class, ctype class template, isalpha function template, islower function template
Determine whether a character is a hexadecimal digit in a locale
template <typename charT> bool isxdigit(charT c, const locale& loc);
The isxdigit
function determines whether the character c
is a hexadecimal digit in the locale loc
. It returns the following:
use_facet<ctype<charT> >(loc).is(ctype_base::xdigit, c)
ctype_base class, ctype class template, isdigit function template
Represent a locale as a set of facets
class locale { public: class facet; class id; typedef int category; static const category none, collate, ctype, monetary, numeric, time, messages, all = collate|ctype|monetary|numeric|time|messages; // construct/copy/destroy: locale() throw(); locale(const locale& other) throw(); explicit locale(const char* std_name); locale(const locale& other, const char* std_name,category); template <typename Facet> locale(const locale& other, Facet* f); locale(const locale& other, const locale& one, category); ~locale() throw(); const locale& operator=(const locale& other) throw(); template <typename Facet> locale combine(const locale& other) const; basic_string<char> name() const; bool operator==(const locale& other) const; bool operator!=(const locale& other) const; template <typename charT, typename Traits, typename Alloc> bool operator()(const basic_string<charT,Traits,Alloc>& s1, const basic_string<charT,Traits,Alloc>& s2) const; static locale global(const locale&); static const locale& classic(); };
The locale
class template represents the information for a locale. This information is stored as a set of facets. Several facets are defined by the C++ standard, and user-defined facets can be added to any locale. The has_facet
function tests whether a locale supports a particular facet. The use_facet
function retrieves a facet of a locale.
A locale is immutable, so references to a facet can be kept safely until the locale object is destroyed. New locales can be created from existing locales, with modifications to a particular facet.
Some locales have names. A locale can be constructed for a standard name, or a named locale can be copied or combined with other named locales to produce a new named locale.
When interacting with the user, either through the standard I/O streams or through a graphical user interface, you should use the native locale, that is, locale("")
. When performing I/O, especially to external files, where the data must be portable to other programs, systems, or environments, always use the "C"
locale (locale::classic()
).
Example 13-28 shows an example of using locales to control input and output formats.
Example 13-28: Using locales for input and output.
// Open a file and read floating point numbers from it, // computing the mean. Return the mean or 0 if the file // contains no data. The data are in the classic format, // that is, the same format used by C++. double mean(const char* filename) { std::ifstream in(filename); // Force the data file to be interpreted in the classic // locale, so the same data file can be used everywhere. in.imbue(std::locale::classic()); double sum = 0; unsigned long count = 0; std::istream_iterator<double> iter(in), end; for ( ; iter != end; ++iter) { ++count; sum += *iter; } return count == 0 ? 0.0 : sum / count; } int main(){ // cout is automatically imbued with the global locale. std::cout << mean("data.txt") << '\n'; }
Following are the member functions of locale
:
locale
() throw()
locale::classic()
.
locale
(const locale& other)
throw()
other
locale.explicit
locale
(const char* std_name)
locale
is initialized using a standard name. The names "C"
and ""
are always defined, where "C"
is the locale returned by the classic()
function, and ""
identifies the implementation-defined native locale."en_US"
identifies the locale for US English.
locale
(const locale& other, const char* std_name, category mask)
locale
is copied from other
, except for those categories identified by mask
, which are copied from the standard locale identified by std_name
. The new locale has a name only if other
has a name.template <typename Facet>
locale
(const locale& other, Facet* f)
locale
is copied from other
except the facet Facet
, which is obtained from f
if f
is not null.
locale
(const locale& other, const locale& one, category mask)
locale
is copied from other
except for those categories identified by mask
, which are copied from one
. The new locale has a name only if other
and one
have names.template <typename Facet>
locale
combine
(const locale& other) const
combine
function returns a new locale that is a copy of *this
except for Facet
, which is copied from other. If other
does not support the facet, that is, has_facet<Facet>(other)
is false, runtime_error
is thrown. The new locale has no name.basic_string<char>
name
()
const
name
function returns the locale's name or "*"
if the locale has no name. The exact contents of the name string are implementation-defined, but you can use the string to construct a new locale that is equal to *this
, that is, *this
==
locale(name().c_str())
.const locale&
operator=
(const locale& other) throw()
other
and returns *this
.bool
operator==
(const locale& other)
const
==
operator returns true if the two locales are the same object, one locale object is a copy of the other, or the two locales are named and have the same name. Otherwise, the function returns false.bool
operator!=
(const locale& other)
const
!=
operator returns !(*this
==
other)
.template
<typename charT, typename Tr, typename A>
bool
operator()
(const basic_string<charT, Tr, A>& s1,
const basic_string<charT,Tr,A>& s2)
const
collate<charT>
facet and returns true if s1
<
s2
. You can use the locale object as a comparator predicate to compare strings. See <string>
for more information.static
locale
global
(const locale& loc)
global
function sets the global locale to loc
and returns the previous global locale. If the new locale has a name, the C locale is set by calling setlocale(LC_ALL,
loc.name().c_str())
; if the locale does not have a name, the effect on the C locale is implementation-defined.static
const
locale&
classic
()
classic
function returns a locale that implements the "C"
locale.has_facet function template, use_facet function template, setlocale in <clocale>
Bitmask of facet categories
typedef int category; static const category none, collate, ctype, monetary, numeric, time, messages, all = collate|ctype|monetary|numeric|time|messages;
The category
type is an int
, representing a bitmask of category identifiers, as listed in Table 13-20. Each category represents a set of one or more related facets. When combining locales, you can copy all the facets in one or more categories. Category identifiers can be combined using bitwise operators.
Literal | Facets |
---|---|
collate |
collate<char> , collate<wchar_t> |
ctype |
ctype<char> , ctype<wchar_t> , codecvt<char,char,mbstate_t> ,codecvt<wchar_t,char,mbstate_t> |
messages |
messages<char> , messages<wchar_t> |
monetary |
money_get<char> , money_get<wchar_t> ,money_put<char> , money_put<wchar_t> ,moneypunct<char> , moneypunct<wchar_t> ,moneypunct<char,true> , moneypunct<wchar_t,true> |
numeric |
num_get<char> , num_get<wchar_t> ,num_put<char> , num_put<wchar_t> ,numpunct<char> , numpunct<wchar_t> |
time |
time_get<char> , time_get<wchar_t> ,time_put<char> , time_put<wchar_t> |
locale class
Base class for locale facets
class locale::facet { protected: explicit facet(size_t refs = 0); virtual ~facet(); private: facet(const facet&); // not defined void operator=(const facet&); // not defined };
The facet
class is the base class for all facets. A derived class must also declare a public data member of type locale::id
whose name is id
. Any other methods for a custom facet are entirely up to the programmer; the derived class does not need to provide a copy or default constructor or an assignment operator.
The locale
class assigns a value to id
when the facet object is added to a locale. You never need to examine or alter the id
member; it is managed entirely by locale
.
The explicit constructor for facet
takes a single argument, ref. If ref
==
0
, the facet
object is not deleted when the last locale that uses the facet is destroyed. If ref
==
1
, the facet
object is never destroyed. The standard facet classes (ctype
, etc.) also take a ref
parameter and pass it directly to the inherited facet
constructor. Custom facets can do whatever the programmer wants, such as relying on the default value of zero to manage the facet's lifetime automatically.
For example, suppose you want to define a facet that captures the locale-specific preferences for units of measure, such as length and weight. The program can store and manipulate values in a common base unit, and convert to the preferred unit for output. Example 13-29 shows the units
facet and its use.
Example 13-29: A simple facet for working with units of measure.
class units : public std::locale::facet { public: enum length_units { length_base=1, mm=10, cm=10*mm, m=10*cm, km=1000*m, in=254, ft=12*in, yd=3*ft, mi=5280*ft }; typedef double value_t; // All facets must have a static id member. static std::locale::id id; // Constructor initializes length_units_ according to // local preferences. units(); // Read a length and its units, and return the length // in base units. value_t length_get(std::istream& stream) const; // Convert value to the preferred units, and print the // converted value followed by the unit name. void length_put(std::ostream& stream, value_t value) const // Make a base unit value from a value in src_units. value_t make(value_t src_value, length_units src_units) const // Convert base units to dst_unit. value_t convert(value_t src_value, length_units dst_units) const // Return the name of a unit. const char* unit_name(length_units units) const; // Return the preferred unit for length. length_units get_length_unit() const; private: length_units length_units_; }; int main() { // Add the units facet to the global locale: // 1. Construct a new locale that is a copy of the global // locale, with the new units facet added to it. // 2. Set the new locale as the global locale. std::locale loc(std::locale(std::locale(), new units)); std::locale::global(loc); // Now anyone can get the units facet from the // global locale. const units& u = std::use_facet<units>(std::locale()); units::value_t size = u.make(42, units::cm); u.put_length(size, std::cout); }
locale class, locale::id class
Facet identification
class locale::id { public: id(); private: void operator=(const id&); // not defined id(const id&); // not defined };
The id
class identifies a facet. The only use is to declare a public, static member of type locale::id
in every facet class. See locale::facet
for more information.
locale::facet class
Facet for retrieving strings from a message catalog
template <typename charT> class messages : public locale::facet, public messages_base { public: typedef charT char_type; typedef basic_string<charT> string_type; explicit messages(size_t refs = 0); catalog open(const basic_string<char>& fn, const locale&) const; string_type get(catalog c, int set, int msgid, const string_type& dfault) const; void close(catalog c) const; static locale::id id; protected: virtual ~messages(); virtual catalog do_open(const basic_string<char>&, const locale&) const; virtual string_type do_get(catalog, int set, int msgid, const string_type& dfault) const; virtual void do_close(catalog) const; };
The messages
class template is a facet for a message catalog. A message catalog is a database of textual messages that can be translated into different languages.
The messages<char>
and messages<wchar_t>
instantiations are standard.
How a message catalog is found is implementation defined. For example, a catalog name might be the name of an external file, or it could be the name of a special resource section in the program's executable file. The mapping of message identifiers to a particular message is also implementation defined.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as get
, which calls do_get
. The descriptions below are for the virtual functions because they do the real work.
virtual
void
do_close
(catalog
cat)
const
do_close
function closes the message catalog cat
.virtual
string_type
do_get
(catalog
cat,
int
set,
int
msgid,
const
string_type&
dfault)
const
do_get
function gets a message that is identified by set
, msgid
, and dfault
from catalog cat
. If the message cannot be found, dfault
is returned. virtual
catalog
do_open
(const
basic_string<char>&
name,
const
locale&
loc)
const
do_open
function opens a message catalog name
. If the catalog cannot be opened, a negative value is returned. Otherwise, the catalog
value can be passed to get
to retrieve messages. Call close
to close the catalog.messages_base class, messages_byname class template
Base class for message facets
class messages_base { public: typedef int catalog; };
The message_base
class is the base class for messages
and message_byname
. It declares the catalog
type, which stores a handle for an open message catalog.
messages class template, message_byname class template
Facet for retrieving strings from a message catalog
template <typename charT> class messages_byname : public messages<charT> { public: typedef messages_base::catalog catalog; typedef basic_string<charT> string_type; explicit messages_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in messages };
The messages_byname
class template is a facet for a message catalog, using a named locale. The messages_byname<char>
and messages_byname<wchar_t>
instantiations are standard.
messages class template, messages_base class
Base class for moneypunct facet
class money_base { public: enum part { none, space, symbol, sign, value }; struct pattern { char field[4]; }; };
The money_base
class is a base class for the moneypunct
and moneypunct_byname
class templates. It declares the part
and pattern
types. A pattern
actually stores four part
values, but they are stored as four char
values for efficiency. See moneypunct
for an explanation of how part
and pattern
are used.
moneypunct class template, moneypunct_byname class template
Facet for input of monetary values
template <typename charT, typename InputIterator = istreambuf_iterator<charT> > class money_get : public locale::facet { public: typedef charT char_type; typedef InputIterator iter_type; typedef basic_string<charT> string_type; explicit money_get(size_t refs = 0); iter_type get(iter_type s, iter_type end, bool intl, ios_base& f, ios_base::iostate& err, long double& units) const; iter_type get(iter_type s, iter_type end, bool intl, ios_base& f, ios_base::iostate& err, string_type& digits) const; static locale::id id; protected: virtual ~money_get(); virtual iter_type do_get(iter_type begin, iter_type end, bool intl, ios_base& strean, ios_base::iostate& err, long double& units) const; virtual iter_type do_get(iter_type begin, iter_type end, bool intl, ios_base& stream, ios_base::iostate& err, string_type& digits) const; };
The money_get
class template is a facet for parsing monetary values from an input stream. The money_get<char>
and money_get<wchar_t>
instantiations are standard. Example 13-30 shows a simple use of money_get
and money_put
.
Example 13-30: Reading and writing monetary values.
#include <iostream> #include <locale> int main() { std::ios_base::iostate err = std::ios_base::goodbit; long double value; std::cout << "What is your hourly wage? "; std::use_facet<std::money_get<char> >(std::locale()).get( std::cin, std::istreambuf_iterator<char>(), false, std::cin, err, value); if (err) std::cerr << "Invalid input\n"; else { std::cout << value << '\n'; std::cout << "You make "; std::use_facet<std::money_put<char> >(std::locale()).put( std::cout, false, std::cout, std::cout.fill(), value * 40); std::cout << " in a 40-hour work week.\n"; } }
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public function get
, which calls do_get
. The description below is for the virtual functions because they do the real work.
virtual
iter_type
do_get
(iter_type
begin,
iter_type end,
bool
intl,
ios_base&
stream,
ios_base::iostate&
err,
long double&
units) const
virtual
iter_type
do_get
(iter_type
begin,
iter_type end, bool
intl,
ios_base&
stream,
ios_base::iostate&
err,
string_type&
digits)
const
do_get
function reads characters in the range [begin
, end
) and interprets them as a monetary value. If intl
is true, the value is parsed using international format; otherwise local format is used. That is, the intl
value is used as the Intl
template parameter to moneypunct<char_type,
Intl>
, to get the neg_format()
pattern. If a valid monetary value is read from the input stream, the integral value is stored in units
or is formatted as a string in digits
. (For example, the input "$1,234.56"
yields the units 123456
or the digits "123456"
.) The digit string starts with an optional minus sign ('-'
), followed by digits ('0'
to '9'
), where each character c
is produced by calling ctype<char_type>.widen(c)
.err
is modified to include stream.failbit
. If the end of the input is reached without forming a valid monetary value, stream.eofbit
is also set.showbase
flag is set (stream.flags()
&
stream
.showbase
is not zero), the currency symbol is required; otherwise it is optional. Thousands grouping, if the local supports it, is optional.positive_sign()
and negative_sign()
.money_put class template, moneypunct class template, num_get class template
Facet for output of monetary values
template <typename charT, typename OutputIterator = ostreambuf_iterator<charT> > class money_put : public locale::facet { public: typedef charT char_type; typedef OutputIterator iter_type; typedef basic_string<charT> string_type; explicit money_put(size_t refs = 0); iter_type put(iter_type s, bool intl, ios_base& f, char_type fill, long double units) const; iter_type put(iter_type s, bool intl, ios_base& f, char_type fill, const string_type& digits) const; static locale::id id; protected: virtual ~money_put(); virtual iter_type do_put(iter_type, bool, ios_base&, char_type fill, long double units) const; virtual iter_type do_put(iter_type, bool, ios_base&, char_type fill, const string_type& digits) const; };
The money_put
class template is a facet for formatting and printing monetary values. See Example 13-30 (under money_get
, earlier in this section) for an example of using the money_put
facet.
The money_put<char>
and money_put<wchar_t>
instantiations are standard.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as put
, which calls do_put
. The descriptions below are for the virtual functions because they do the real work.
virtual
iter_type
do_put
(iter_type
iter,
bool
intl,
ios_base&
stream,
char_type
fill,
long
double
units)
const
virtual
iter_type
do_put
(iter_type
iter,
bool
intl,
ios_base&
stream,
char_type fill,
const string_type& digits)
const
do_put
function formats a monetary value and writes the formatted characters to iter
. The value to format is either an integer, units
, or a string of digit characters in digits
. If the first character of digits is widen('-')
, the remaining digits are interpreted as a negative number.moneypunct
facet. For positive value, pos_format()
is used; for negative values, neg_format()
is used. The pattern dictates the output format. (See moneypunct
, later in this section, for information on patterns.) The currency symbol is printed only if the showbase
flag is set (that is, stream.flags()
&
stream.showbase
is not zero). Thousands separators and a decimal point are inserted at the appropriate places in the formatted output.fill
characters are inserted until the formatted width is stream.width().
The stream's adjustfield
flags dictates how fill characters are inserted. That is, stream.flags()
&
stream.adjustfield
is tested, and if it is equal to:stream.internal
: fill characters are inserted where the pattern is none
or space
;stream.left
: fill characters are appended to the end of the formatted field;stream.width(0)
is called to reset the field width to zero. The return value is an iterator that points to one past the last output character.money_get class template, moneypunct class template, num_put class template
Facet for punctuation of monetary values
template <typename charT, bool International = false> class moneypunct : public locale::facet, public money_base { public: typedef charT char_type; typedef basic_string<charT> string_type; explicit moneypunct(size_t refs = 0); charT decimal_point() const; charT thousands_sep() const; string grouping() const; string_type curr_symbol() const; string_type positive_sign() const; string_type negative_sign() const; int frac_digits() const; pattern pos_format() const; pattern neg_format() const; static locale::id id; static const bool intl = International; protected: virtual ~moneypunct(); virtual charT do_decimal_point() const; virtual charT do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_curr_symbol() const; virtual string_type do_positive_sign() const; virtual string_type do_negative_sign() const; virtual int do_frac_digits() const; virtual pattern do_pos_format() const; virtual pattern do_neg_format() const; };
The moneypunct
class template is a facet that describes the punctuation characters used to format a monetary value.
The moneypunct<char,false>
, moneypunct<wchar_t,false>
, moneypunct<char,true>
, and moneypunct<wchar_t,true>
instantiations are standard.
The International
template parameter is true for an international format or false for a local format. In an international format, the currency symbol is always four characters, and usually three characters followed by a space.
The money_get
and money_put
facets use a pattern to parse or format a monetary value. The pattern specifies the order in which parts of a monetary value must appear. Each pattern has four fields, where each field has type part
(cast to char
). The symbol
, sign
, and value
parts must appear exactly once, and the remaining field must be space
or none
. The value none
cannot be first (field[0]
); space
cannot be first or last (field[3]
).
Where sign appears in the pattern, the first character of the sign string (positive_sign()
or negative_sign())
is output,and the remaining characters of the sign string appear at the end of the formatted output. Thus, if negative_sign()
returns "()"
, the value -12.34 might be formatted as "(12.34)"
.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as grouping
, which calls do_grouping
. The descriptions below are for the virtual functions because they do the real work.
virtual
string_type
do_curr_symbol
()
const
do_curr_symbol
function returns the currency symbol, such as "$"
(which is used by some U.S. Locales) or "USD "
(which is the international currency symbol for U.S. Dollars). In the "C"
locale, the currency symbol is ""
or L""
.virtual
charT
do_decimal_point
()
const
do_decimal_point
function returns the character used before the fractional part when do_frac_digits
is greater than zero. For example, in the U.S., this is typically '.'
, and in Europe, it it typically ','
. In the "C"
locale, the decimal point is "."
or L"."
.virtual
int
do_frac_digits
()
const
do_frac_digits
function returns the number of digits to print after the decimal point. This value can be zero. In the "C"
locale, the number of digits is std::limits<char>.max().virtual
string
do_grouping
()
const
do_grouping
function returns a string that specifies the positions of thousands separators. The string is interpreted as a vector of integers, where each value is a number of digits, starting from the right. Thus, groups of 3 digits is expressed as the string "\3"
. In the "C"
locale, the grouping is ""
or L""
.virtual
pattern
do_neg_format
()
const
do_neg_format
function returns the pattern used to format negative values. In the "C"
locale, the negative format is {
symbol,
sign,
none,
value
}
.virtual
string_type
do_negative_sign
()
const
do_negative_sign
function returns the string (which may be empty) used for negative values. The position of the sign is dictated by the do_neg_format
pattern. In the "C"
locale, the negative sign is "-"
or L"-"
.virtual
pattern
do_pos_format
()
const
do_pos_format
function returns the pattern used to format positive values.In the "C"
locale, the positive format is {
symbol,
sign,
none,
value
}
.virtual
string_type
do_positive_sign
()
const
do_positive_sign
function returns the string (which may be empty) used for positive values. The position of the sign is dictated by the do_pos_format
pattern. In the "C"
locale, the positive sign is ""
or L""
.virtual
charT
do_thousands_sep
()
const
do_thousands_sep
function returns the character used to separate groups of digits, where the groups are specified by do_grouping
. In the U.S., the separator is typically '.'
, and in Europe it is often '.'
. In the "C"
locale, the thousands separator is ","
or L","
.money_base class, money_get class template, money_put class template, moneypunct_byname class template, numpunct class template
Facet for punctuation of monetary values
template <typename charT, bool Intl = false> class moneypunct_byname : public moneypunct<charT, Intl> { public: typedef money_base::pattern pattern; typedef basic_string<charT> string_type; explicit moneypunct_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in moneypunct };
The moneypunct_byname
class template provides formatting characters and information for monetary values, using the rules of a named locale. The moneypunct_byname<char,International>
and moneypunct_byname<wchar_t,International>
instantiations are standard.
moneypunct class template
Facet for input of numbers
template <typename charT, typename InputIterator = istreambuf_iterator<charT> > class num_get : public locale::facet { public: typedef charT char_type; typedef InputIterator iter_type; explicit num_get(size_t refs = 0); iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, bool& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, long& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned short& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned int& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, unsigned long& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, float& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, double& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, long double& v) const; iter_type get(iter_type in, iter_type end, ios_base&, ios_base::iostate& err, void*& v) const; static locale::id id; protected: virtual ~num_get(); virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, bool& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned short& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned int& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, unsigned long& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, float& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, double& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, long double& v) const; virtual iter_type do_get(iter_type, iter_type, ios_base&, ios_base::iostate& err, void*& v) const; };
The num_get
class template is a facet for parsing and reading numeric values from an input stream. The istream
extraction operators (>>)
use num_get
.
The num_get<char>
and num_get<wchar_t>
instantiations are standard.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as get
, which calls do_get
. The descriptions below are for the virtual functions because they do the real work.
virtual
iter_type
do_get
(iter_type
begin,
iter_type
end,
ios_base&
stream,
ios_base::iostate&
err,
bool&
v)
const
do_get
function for a bool value first tests the boolalpha
flag: if stream.flags()
&
stream.boolalpha
is zero, a long
value is read from begin
. If the value is 1, v
is assigned true
; if the value is 0, v
is assigned false
; otherwise, failbit
is set in err
and v
is not modified.boolalpha
is true, characters are read from begin
until one of the following happens:truename()
from the numpunct
facet, that is,use_facet<numpunct<char_type> >(stream.getloc()).truename()
in which case,v
is assignedtrue
, anderr
is assignedgoodbit
. A match is determined by the shortest input sequence that uniquely matchestruename()
orfalsename()
.
falsename():
v
is assigned false
, and err
is assigned goodbit
;begin
==
end
, in which case eofbit
is set in err
;truename()
or falsename()
: failbit
is set in err
.virtual
iter_type
do_get
(iter_type
begin,
iter_type
end,
ios_base&
stream,
ios_base::iostate&
err,
type&
v)
const
do_get
function is overloaded for most of the fundamental types. The behavior of each function is essentially the same, and depends on stream.flags()
, the ctype
facet and the numpunct
facet. Both facets are obtained for the locale stream.getloc()
.begin
, end
) or until the input character is not part of a valid number according to the flags and numpunct
facet. A locale-dependent decimal point is replaced with the character '.'
. Thousands separators are read but not checked for valid positions until after the entire number has been read. The set of valid characters depends on the type of v
and the flags, in particular the basefield
flags. If stream.flags()
&
basefield
is hex
, hexadecimal characters are read; if oct
, only octal characters are read ('0'
to '7'
). If the basefield
is 0, the prefix determines the radix: 0x
or 0X
for hexadecimal, 0
for octal, and anything else is decimal. Floating point numbers can use fixed or exponential notation.v
is of type void*
, the format is implementation-defined, in the same manner as the %p
format for scanf (in <cstdio>
).failbit
is set in err
and v
is not changed. If the string is valid, its numeric value is stored in v
and err
is set to goodbit
. If the entire input stream is read (up to end
), eofbit
is set in err
.money_get class template, num_put class template, numpunct class template, istream in <istream>
Facet for output of numbers
template <typename charT, typename OutputIterator = ostreambuf_iterator<charT> > class num_put : public locale::facet { public: typedef charT char_type; typedef OutputIterator iter_type; explicit num_put(size_t refs = 0); iter_type put(iter_type s, ios_base& f, char_type fill, bool v) const; iter_type put(iter_type s, ios_base& f, char_type fill, long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, unsigned long v) const; iter_type put(iter_type s, ios_base& f, char_type fill, double v) const; iter_type put(iter_type s, ios_base& f, char_type fill, long double v) const; iter_type put(iter_type s, ios_base& f, char_type fill, const void* v) const; static locale::id id; protected: virtual ~num_put(); virtual iter_type do_put(iter_type, ios_base&, char_type fill, bool v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, long v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, unsigned long) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, double v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, long double v) const; virtual iter_type do_put(iter_type, ios_base&, char_type fill, const void* v) const; };
The num_put
class template is a facet for formatting and outputing a numeric value. The ostream
output operators (>>
) use num_put
.
The num_put<char>
and num_put<wchar_t>
instantiations are standard.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as put
, which calls do_put
. The descriptions below are for the virtual functions because they do the real work.
virtual
iter_type
do_put
(iter_type
out,
ios_base&
stream,
char_type
fill,
bool
v)
const
do_put
function writes a bool
value to out
. If the boolalpha
flag is not set, that is, stream.flags()
&
stream.boolalpha
is zero, the integer value of v
is written as a number. Otherwise, if v
is true, truename()
is written or if v
is false, falsename()
is written, using the numpunct
facet, e.g.,const numpunct<charT>& n = use_facet<numpunct<charT> >; string_type s = v ? n.truename() : n.falsename(); // write characters of s to out
virtual
iter_type
do_put
(iter_type
out,
ios_base&
stream,
char_type
fill,
type v)
const
do_put
function formats v
as a string and writes the string contents to out
, using the flags of stream
to control the formatting and the imbued locale of stream
to obtain the ctype
and numpunct
facets for punctuation rules and characters. The format also depends on type:long
, unsigned
long
): the format depends on the basefield
flags (stream.flags()
&
basefield
). If oct
, the number is formatted as octal; if hex
, the number is formatted as hexadecimal (using 'a'
through 'f'
for the digits 10 to 16, or 'A'
through 'F'
if the uppercase
flag is set); or else the number is decimal. If the showbase
flag is set, a prefix is used: 0
for octal, or 0x
or 0X
for hexadecimal (depending on the uppercase
flag).double
, long
double
): the format depends on the floatfield
flags (stream.flags()
&
floatfield
). If fixed
, the format is fixed point: an integer part, a decimal point, and a fractional part. If scientific
, the format is exponential.Otherwise, a general format is used: exponential if the exponent is -4 or less or greater than the precision (number of places after the decimal point); fixed otherwise. Trailing zeros are dropped, as is the decimal point if would be the last character in the string.
If theuppercase
flag is set, the exponent is introduced by'E'
, else by'e'
. If theshowpoint
flag is set, the decimal point is always present.
void*
): the format is implementation-defined.'-'
). If the number is positive, nothing is output unless the showpos
flag is set, in which case a positive sign ('+'
) appears at the start of the string.fill
characters are inserted until the formatted width is stream.width().
The stream's adjustfield
flags dictates how fill characters are inserted. That is, stream.flags()
&
stream.adjustfield
is tested, and if it is equal to:stream.internal
: fill characters are inserted after a sign (if present), or if there is no sign, after a leading 0x
or 0X
, or else at the start of the field;stream.left
: fill characters are appended to the end of the formatted field;stream.width(0)
is called to reset the field width to zero. The return value is an iterator that points to one past the last output character.money_put class template, num_get class template, numpunct class template, ostream in <ostream>
Facet for punctuation of numbers
template <typename charT> class numpunct : public locale::facet { public: typedef charT char_type; typedef basic_string<charT> string_type; explicit numpunct(size_t refs = 0); char_type decimal_point() const; char_type thousands_sep() const; string grouping() const; string_type truename() const; string_type falsename() const; static locale::id id; protected: virtual ~numpunct(); virtual char_type do_decimal_point() const; virtual char_type do_thousands_sep() const; virtual string do_grouping() const; virtual string_type do_truename() const; virtual string_type do_falsename() const; };
The numpunct
class template is a facet for numeric formatting and punctuation. The num_get
and num_put
facets use numpunct.
The numpunct<char>
and numpunct<wchar_t>
instantiations are standard.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as grouping
, which calls do_grouping
. The descriptions below are for the virtual functions because they do the real work.
virtual
char_type
do_decimal_point
()
const
do_decimal_point
function returns the decimal point character, which is typically '.'
in U.S. locales, and ','
in European locales. In the "C"
locale, the decimal point is "."
or L"."
.virtual string_type
do_falsename
() const
do_falsename
function returns the textual representation for the value false
. In the standard instantiations (numpunct<char>
and numpunct<wchar_t>
), the value is "false"
or L"false"
.virtual
string
do_grouping
()
const
do_grouping
function returns a string that specifies the positions of thousands separators. The string is interpreted as a vector of integers, where each value is a number of digits, starting from the right. Thus, groups of 3 digits is expressed as the string "\3"
. In the "C"
locale, the grouping is ""
or L""
.virtual
char_type
do_thousands_sep
()
const
do_thousands_sep
function returns the character used to separate digit groups (see do_grouping
, earlier in this section). In U.S. locales, this is typically ','
, and in European locales, it is usually '.'
. In the "C"
locale, the thousands separator is ","
or L","
.virtual
string_type
do_truename
()
const
do_truename
function returns the textual representation for the value true
. In the standard instantiations (numpunct<char>
and numpunct<wchar_t>
), the value is "true"
or L"true"
.moneypunct class template, num_get class template, num_put class template
Facet for punctuation of numbers
template <typename charT> class numpunct_byname : public numpunct<charT> { // This class is specialized for char and wchar_t. public: typedef charT char_type; typedef basic_string<charT> string_type; explicit numpunct_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in numpunct };
The numpunct_byname
class templat is a facet for numeric formatting and punctuation, using the rules of a named locale. The numpunct_byname<char>
and numpunct_byname<wchar_t>
instantiations are standard.
numpunct class template
Base class for time facets
class time_base { public: enum dateorder { no_order, dmy, mdy, ymd, ydm }; };
The time_base
class is a base class for the time_get
class template. It declares the dateorder type. See time_get
for more information.
time_get class template
Facet for input of dates and times
template <typename charT, typename InputIterator = istreambuf_iterator<charT> > class time_get : public locale::facet, public time_base { public: typedef charT char_type; typedef InputIterator iter_type; explicit time_get(size_t refs = 0); dateorder date_order() const; iter_type get_time(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_date(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_weekday(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_monthname(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; iter_type get_year(iter_type s, iter_type end, ios_base& f, ios_base::iostate& err, tm* t) const; static locale::id id; protected: virtual ~time_get(); virtual dateorder do_date_order() const; virtual iter_type do_get_time(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_date(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_weekday(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_monthname(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; virtual iter_type do_get_year(iter_type s, iter_type end, ios_base&, ios_base::iostate& err, tm* t) const; };
The time_get
class template is a facet for parsing and reading dates and times from an input stream. The components of the date and time value are stored in a tm
structure. (See <ctime>
for more information about tm
.)
The time_get<char>
and time_get<wchar_t>
instantiations are standard.
Most of the time_get
functions take an err
parameter, much the way other facets and their functions do. Unlike other facets, though, the time_get
functions do not set err
to goodbit
upon success. Instead, they only set failbit
for an error. They do not set eofbit
if the end of the input sequence is reached. If the functions fail, the state of the t
parameter is undefined.
As with other facets, the public members call virtual protected members with the same name prefaced by do_
. Thus, to use the facet, call the public functions, such as get_date
, which calls do_get_date
. The descriptions below are for the virtual functions because they do the real work.
virtual
dateorder
do_date_order
()
const
do_date_order
function returns the order in which the day, month, and year appears in a locale-specific date. If the formatted date includes additional elements, the return value is no_order
. See the time_base
class for the declaration of the dateorder
type.virtual
iter_type
do_get_time
(iter_type
in,
iter_type
end,
ios_base&
stream,
ios_base::iostate&
err, tm* t)
const
do_get_time
function reads characters from [in
, end
) and interprets them as a time, according to the format of time_put<>::put
using the 'X'
format. The time elements are stored in t
. If the input is invalid, the state of t
's members is undefined and err
is set to failbit
. The return value is an iterator that points to one past where the input stoppedvirtual
iter_type
do_get_date
(iter_type
in,
iter_type
end,
ios_base&
stream,
ios_base::iostate&
err,
tm*
t)
const
do_get_date
function reads characters from [in
, end
) and interprets them as a date, according to the format of time_put<>::put
using the 'x'
format. The date elements are stored in t
. If the input is invalid, the state of t
's members is undefined and err
is set to failbit
. The return value is an iterator that points to one past where the input stoppedvirtual iter_type
do_get_weekday
(iter_type in,
iter_type end, ios_base& stream,
ios_base::iostate& err,
tm* t) const
do_get_weekday
function reads characters from [in
, end
) until it reads the name of a day of the week, either abbreviated or in full. The appropriate date elements are stored in t
. If the input is invalid, the state of t
's members is undefined and err
is set to failbit
. The return value is an iterator that points to one past where the input stoppedvirtual iter_type
do_get_monthname
(iter_type in,
iter_type
end,
ios_base&
stream,
ios_base::iostate&
err,
tm*
t)
const
do_get_monthname
function reads characters from [in
, end
) until it reads the name of a month, either abbreviated or in full. The appropriate date elements are stored in t
. If the input is invalid, the state of t
's members is undefined and err
is set to failbit
. The return value is an iterator that points to one past where the input stoppedvirtual iter_type
do_get_year
(iter_type in,
iter_type end, ios_base& stream,
ios_base::iostate& err, tm* t) const
do_get_year
function reads characters from [in
, end
) until it reads a year. It is up to the implementation whether two-digit years are accepted, and if so, which century to apply to the abbreviate year.t->tm_year
member is set appropriately. If the input is invalid, the state of t
's members is undefined and err
is set to failbit
. The return value is an iterator that points to one past where the input stoppedtime_base class, time_get_byname class template, time_put class template, tm in <ctime>
Facet for input of dates and times
template <typename charT, typename InputIterator = istreambuf_iterator<charT> > class time_get_byname : public time_get<charT, InputIterator> { public: typedef time_base::dateorder dateorder; typedef InputIterator iter_type; explicit time_get_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in time_get };
The time_get_byname
class template is a facet for reading dates and times from an input stream, using a named locale. The time_get_byname<char>
and time_get_byname<wchar_t>
instantiations are standard.
time_get class template
Facet for output of dates and times
template <typename charT, typename OutputIterator = ostreambuf_iterator<charT> > class time_put : public locale::facet { public: typedef charT char_type; typedef OutputIterator iter_type; explicit time_put(size_t refs = 0); iter_type put(iter_type s, ios_base& f, char_type fill, const tm* tmb, const charT* pattern, const charT* pat_end) const; iter_type put(iter_type s, ios_base& f, char_type fill, const tm* tmb, char format, char modifier = 0) const; static locale::id id; protected: virtual ~time_put(); virtual iter_type do_put(iter_type s, ios_base&, char_type, const tm* t, char format, char modifier) const; };
The time_put
class template is a facet for formatting and writing dates and times. The time_put<char>
and time_put<wchar_t>
instantiations are standard.
Note that time_put
is unlike other facets. The public put
function does not always directly call do_put
. The complete descriptions of put
and do_put
follow.
iter_type
put
(iter_type out, ios_base& stream,
char_type fill, const tm* t, const charT* pattern,
const charT* pat_end) const
put
function reads the pattern in [pattern
, pat_end
), and writes formatted date and time information to out
. The pattern contains ordinary characters (which are written directly to out
) interspersed with format specifiers, which start with '%'
, followed by an optional modifier character, followed by a format specifier character. The put
function checks format characters by first calling narrow
from the ctype<charT>
facet, and checking the narrowed character.put
calls do_put(out,
stream,
fill,
t,
format,
modifier)
, where format
is the format specifier and modifier
is the modifier character or 0 if no modifier is present.iter_type
put
(iter_type out, ios_base& stream,
char_type fill, const tm* t, char format,
char modifier = 0) const
put
function returns do_put(out,
stream,
fill,
t,
format,
modifier)
.virtual iter_type
do_put
(iter_type out,
ios_base& stream,
char_type fill, const tm* t,
char format, char modifier) const
do_put
function formats a single date or time element and writes the formatted characters to out
. The format
character specifies what to output, as shown in Table 13-20. The date and time information is obtained from t
.do_put
function, unlike some of the other output facets, does not use stream
's flags or field width. The fill
parameter is for use by implementation-defined formatting.modifier
is implementation-defined. The C++ standard recommends the use of POSIX modifiers, which are 'E'
and 'O'
. These modifiers request the use of an alternative format, if the locale has one. The 'E'
modifier applies to certain format specifiers to request an alternative representation for dates and times. The 'O'
modifier applies to certain format specifiers to request the use of alternative numeric symbols. If a locale cannot honor the modified request, it uses the unmodifier format specifier.Specifier | Description |
---|---|
a |
Abbreviated weekday name |
A |
Full weekday name |
b |
Abbreviated month name |
B |
Full month name |
C |
Complete date and time |
D |
Day of the month (01 -31 ) |
H |
Hour (00 -23 ), 24-hour clock |
I |
Hour (01 -12 ), 12-hour clock |
j |
Day of the year (001 -366 ) |
m |
Month (01 -12 ) |
M |
Minutes (00 -59 ) |
P |
AM/PM designation for use with a 12-hour clock |
S |
Second (00 -61 ), up to 2 leap seconds |
U |
Week number (00 -53 ), week 1 starts with the first Sunday |
w |
Weekday (0 -6 ), Sunday is day 0 |
W |
Week number (00 -53 ), week 1 starts with first Monday |
x |
Date |
X |
Time |
y |
Year in century (00 -99 ) |
Y |
Year |
Z |
Time zone name or abbreviation, or empty string if time zone is unknown |
% |
Literal % |
time_get class template, time_put_byname class template, <ctime>
Facet for output of dates and times
template <typename charT, typename OutputIterator = ostreambuf_iterator<charT> > class time_put_byname : public time_put<charT,OutputIterator> { public: typedef charT char_type; typedef OutputIterator iter_type; explicit time_put_byname(const char*, size_t refs = 0); protected: // ... same virtual functions as in time_put };
The time_put
class template is a facet for formatting and writing dates and times, using a named locale. The time_put_byname<char>
and time_put_byname<wchar_t>
instantiations are standard.
time_put class template
Convert a character to lowercase in a locale
template <typename charT> charT tolower(charT c, const locale& loc);
The tolower
function converts the character c
to lowercase using the locale loc
as follows:
use_facet<ctype<charT> >(loc).tolower(c)
ctype class template, islower function template, toupper function template
Convert a character to uppercase in a locale
template <typename charT> charT toupper(charT c, const locale& loc);
The toupper
function converts the character c
to uppercase using the locale loc
as follows:
use_facet<ctype<charT> >(loc).toupper(c)
ctype class template, isupper function template, tolower function template
Retrieve a facet for a locale
template <typename Facet> const Facet& use_facet(const locale& loc)
The use_facet
function template obtains a facet from locale loc
. See Examples 13-27 and 13-30, earlier in this section for several examples of its use.
has_facet function template, locale::facet class