Team LiB   Previous Section   Next Section

13.34 <locale>

The <locale> header declares class and function templates 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. For example, every I/O stream has a locale, which it uses to parse formatted input or to format output.

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 set of related attributes is called a facet, which are grouped into categories.

The categories are fixed and defined by the standard (see Table 13-20, under locale::category, for a complete list), and each category has several predefined facets. For example, one of the facets in the time category is time_get<charT, 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 use this locale for character conversions and formatting. 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>, <cctype>, and <cwchar> headers, especially the ability to extend a locale with your own facets. On the other hand, facets and the locale class template are more complicated than the C functions. For simple character classification in a single locale, you are probably better off using the C functions. If a program must work with multiple locales simultaneously, use the C++ locale template.

codecvt class template 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. It is most often used to convert multibyte characters to and from wide characters.

The following template specializations are required by the standard:

codecvt<wchar_t, char, mbstate_t>

Converts multibyte narrow characters to wide characters (in) and wide to multibyte (out)

codecvt<char, char, mbstate_t>

A no-op, "converting" characters to themselves

As with other facets, the public members of codecvt 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 in turn call do_in and do_out. The descriptions below are for the virtual functions because they do the real work. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

bool always_noconv( ) const throw( )

Returns do_always_noconv( )

The following are the virtual, protected members of codecvt:

virtual bool do_always_noconv( ) const throw( )

Returns true if the codecvt object does not actually perform any conversions, that is, in and out are no-ops. For example, for the specialization codecvt<char,char,mbstate_t>, do_always_noconv always returns true.

virtual int do_encoding( ) const throw( )

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

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.

The 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.

The return value is a result, as described in Table 13-19 (under the codecvt_base class).

virtual int do_length(stateT&, const externT* from, const externT* from_end, size_t max) const

Returns the number of externT characters in the 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( )

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

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.

The 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.

The return value is a result, as described in Table 13-19 (under codecvt_base class).

virtual result do_unshift(stateT& state, externT* to, externT* to_limit, externT*& to_next) const

Ends a shift state by storing characters in the array starting at to such that the characters undo the state shift 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.

The return value is a result, as described in Table 13-19 (under codecvt_base class).

See Also

codecvt_base class, codecvt_byname class template, locale::facet class

codecvt_base 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-19 lists the literals of the result enumerated type.

Table 13-19. codecvt_base::result literals

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 unshift sequence is incomplete

See Also

codecvt class template, codecvt_byname 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,char,mbstate_t> and codecvt_byname<wchar_t,char,mbstate_t> instantiations are standard.

See Also

codecvt class template, locale::facet class

collate class template 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, and 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( ) function uses the collate facet to perform the comparison.

The standard mandates the collate<char> and collate<wchar_t> instantiations, which perform lexicographical (element-wise, numerical) 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. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

int compare(const charT* low1, const charT* high1, const charT* low2, const charT* high2) const

Returns do_compare(low1, high1, low2, high2)

The following are the virtual, protected members of collate:

virtual int do_compare(const charT* low1, const charT* high1, const charT* low2, const charT* high2) const

Compares the character sequences [low1, high1) with the character sequence [low2, high2). The return value is one of the following:

  • -1 if sequence 1 is less than sequence 2

  • 0 if the sequences are equal

  • 1 if sequence 1 is greater than sequence 2

virtual long do_hash (const charT* low, const charT* high) const

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

Transforms the character sequence [low, high) into a string that can be compared (as a simple lexicographical comparison) 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 compare the same character sequence many times.

See Also

collate_byname class template, locale class, locale::facet class

collate_byname class template 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
};

Compares strings using a named locale's collation order. The collate_byname<char> and collate_byname<wchar_t> instantiations are standard.

See Also

collate class template, locale::facet class

ctype class template 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.

figs/acorn.gif

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. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

bool is(mask m, charT c) const

Returns do_is(m, c)

The following are the virtual, protected members of ctype:

virtual bool do_is(mask m, charT c) const
virtual const charT* do_is(const charT* low, const charT* high, mask* dest) const

Classifies a single character c or a sequence of characters [low, high). The first form tests the classification mask, M, of c and returns (M & m) != 0. The second form determines the mask for each character in the range and stores the mask values in the dest array (which must be large enough to hold high - low masks), returning high. See Table 13-19 (under the ctype_base class) 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

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 character cannot be converted to a narrow character, the first function returns dfault, and the second function stores dfault in dest as the narrow version of that character.

virtual const charT* do_scan_is(mask m, const charT* low, const charT* high) const

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 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

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 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

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.

The second form modifies the character sequence: each character in [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

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.

The second form modifies the character sequence: each character in [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

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.

See Also

ctype_base class, ctype_byname class template, locale::facet class

ctype<char> 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 =  . . . ;
  inline bool is(mask m, char c) const;
  inline const char* is(const char* low, const char* high, mask* vec) const;
  inline const char* scan_is(mask m, const char* low, const char* high) const;
  inline const char* scan_not(mask m, const char* low, const char* high) const;
protected:
  virtual ~ctype(  );
  inline const mask* table(  ) const throw(  );
  inline 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 the protected member functions table and classic_table. Each of these functions returns an array of mask values indexed by characters cast to unsigned char. The number of elements in a table must be at least table_size, which is an implementation-defined constant value.

The following are the key member functions:

explicit ctype(const mask* tab = 0, bool del = false, size_t refs = 0)

Initializes the 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 ctype object owns the table, and when the ctype destructor is called, it will delete the table. The refs parameter is passed to the base class, as with any facet.

virtual ~ctype( )

If the constructor's del flag was true, and tab was not a null pointer, performs delete[] tab.

inline bool is(mask m, charT c) const
inline const charT* is(const charT* low, const charT* high, mask* dest) const

Tests character classifications. The first form returns:

(table(  )[static_cast<unsigned char>(c)] & m) != 0

The second form stores the following in dest for each element c of the range [low, high):

table(  )[static_cast<unsigned char>(c)]

Note that is does not call do_is, so is can be implemented as an inline function.

inline static const mask* classic_table( ) throw( )

Returns a table that corresponds to the "C" locale.

inline const char* scan_is(mask m, const char* low, const char* high) const

Searches the sequence of characters [low, high) for the first character that matches m, that is, for which is(m, c) is true. The return value is a pointer to the first matching character, or high if no characters match m.

inline const char* scan_not(mask m, const char* low, const char* high) const

Searches the sequence of characters [low, high) for the first character that does not match m, that is, for which is(m, c) is false. The return value is a pointer to the first matching character, or high if every character matches m.

inline const mask* table( ) throw( )

Returns the value that was passed to the constructor as the tab parameter, or, if tab was null, classic_table( ) is returned.

See Also

ctype class template, locale::facet class, <cctype>, <cwctype>

ctype_base class 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-20 describes the mask literals and their definitions for the classic "C" locale.

Table 13-20. mask literals for classifying characters

Literal

Description

"C" locale

alpha

Alphabetic (a letter)

lower or upper

alnum

Alphanumeric (letter or digit)

alpha or digit

cntrl

Control (nonprintable)

Not print

digit

'0'-'9'

All locales

graph

Character that occupies graphical space

print but not space

lower

Lowercase letter

'a'-'z'

print

Printable character (alphanumeric, punctuation, space, etc.)

Depends on character set; in ASCII: '\x20'-'\x7e')

space

Whitespace

' ', '\f', '\n', '\r', '\t', '\v'

upper

Uppercase letter

'A'-'Z'

xdigit

Hexadecimal digit ('0'-'9', 'a'-'f', 'A'-'F')

All locales

See Also

ctype class template, ctype_byname 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; it uses a named locale. The ctype_byname<char> and ctype_byname<wchar_t> instantiations are standard.

See Also

ctype class template, ctype_byname<char> class

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 and unsigned char.) It derives from ctype<char>, so it inherits its table-driven implementation.

See Also

ctype<char> class, ctype_byname class template

has_facet function 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 loc supports the facet Facet. It returns true if the facet is supported or false if it is 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-24 shows how has_facet is used.

Example

Example 13-24. 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 42 cm.
  units::value_t len = u.make(42, units::cm);
  // Print the length (42 cm) in the locale's preferred units.
  u.length_put(std::cout, len);
}

See Also

locale class, use_facet function template

isalnum function template Determines 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)

See Also

ctype_base class, ctype class template, isalpha function template, isdigit function template

isalpha function template Determines 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)

See Also

ctype_base class, ctype class template, isalnum function template, islower function template, isupper function template

iscntrl function template Determines 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)

See Also

ctype_base class, ctype class template, isprint function template

isdigit function template Determines 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)

See Also

ctype_base class, ctype class template, isalnum function template, isxdigit function template

isgraph function template Determines 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)

See Also

ctype_base class, ctype class template, isalnum function template, isprint function template, ispunct function template

islower function template Determines 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)

See Also

ctype_base class, ctype class template, isalpha function template, isupper function template

isprint function template Determines 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)

See Also

ctype_base class, ctype class template, iscntrl function template, isgraph function template, isspace function template

ispunct function template Determines 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)

See Also

ctype_base class, ctype class template, isgraph function template

isspace function template Determines whether a character is whitespace in a locale

template <typename charT>
bool isspace(charT c, const locale& loc);

The isspace function determines whether the character c is whitespace in the locale loc. It returns the following:

use_facet<ctype<charT> >(loc).is(ctype_base::space, c)

See Also

ctype_base class, ctype class template, isgraph function template, isprint function template

isupper function template Determines 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)

See Also

ctype_base class, ctype class template, isalpha function template, islower function template

isxdigit function template Determines 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)

See Also

ctype_base class, ctype class template, isdigit function template

locale class Represents 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 template tests whether a locale supports a particular facet. The use_facet function template retrieves a facet of a locale.

References to a facet are safe until all locale objects that use that facet have been 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-25 shows locales that control input and output formats.

Example

Example 13-25. 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 is in the classic
// format, that is, the same format used by C++.
double mean(const char* filename)
{
  std::ifstream in(filename);
  // Force the datafile to be interpreted in the classic locale, so the same
  // datafile 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(  )
{
  // Print results in the user's native locale.
  std::cout.imbue(std::locale(""));
  std::cout << mean("data.txt") << '\n';
}

The following are the member functions of locale:

locale( ) throw( )

Initializes the locale with a copy of the current global locale. The initial global locale is locale::classic( ).

locale(const locale& other) throw( )

Copies the other locale.

figs/acorn.gifexplicit locale(const char* std_name)

Initializes the locale using a standard name. The names "C" and "" (empty string) are always defined, in which "C" is the locale returned by the classic( ) function, and "" identifies the implementation-defined native locale.

An implementation can define additional names. Many C++ implementations use ISO language codes and country codes to identify a locale. For example, the ISO 639 language code for English is "en", and the ISO 3166 country code for the United States is "US", so "en_US" could identify the locale for U.S. English.

locale(const locale& other, const char* std_name, category mask)

Copies the locale 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)

Copies the locale from other except for the facet Facet, which is obtained from f if f is not null.

locale(const locale& other, const locale& one, category mask)

Copies the locale 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

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 falseruntime_error is thrown. The new locale has no name.

figs/acorn.gifbasic_string<char> name( ) const

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( )

Copies other and returns *this.

bool operator==(const locale& other) const

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

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

Compares two strings using the 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.

figs/acorn.gifstatic locale global(const locale& loc)

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( )

Returns a locale that implements the "C" locale.

See Also

has_facet function template, use_facet function template, setlocale in <clocale>, <string>

locale::category type 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 and represents a bitmask of category identifiers, as listed in Table 13-21. 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.

Table 13-21. Standard categories and their facets

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>

See Also

locale class

locale::facet 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, static data member of type locale::id whose name is id. Even a derived class must declare its own id member because it must have an identifier that is distinct from that of the base-class facet. Any other members 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 until 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 0 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. A program can store and manipulate values in a common base unit and convert to the preferred unit for output. Example 13-26 shows a units facet that allows you to do these things.

Example

Example 13-26. 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.length_put(std::cout, size);
}

See Also

locale class, locale::id 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. It is used only to declare a public, static member of type locale::id in every facet class. See locale::facet for more information.

See Also

locale::facet class

messages class template 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.

figs/acorn.gif

How a message catalog is found is implementation-defined. For example, a catalog name could 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. Imagine that for each virtual-function description, there is a corresponding description for a public, nonvirtual function, such as:

void close(catalog cat) const

Calls do_close(cat).

The following are the virtual, protected members of messages:

virtual void do_close(catalog cat) const

Closes the message catalog cat.

virtual string_type do_get(catalog cat, int set, int msgid, const string_type& dfault) const

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

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.

See Also

messages_base class, messages_byname class template

messages_base class 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.

See Also

messages class template, message_byname class template

messages_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; it uses a named locale. The messages_byname<char> and messages_byname<wchar_t> instantiations are standard.

See Also

messages class template, messages_base class

money_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 space efficiency. See moneypunct for an explanation of how part and pattern are used.

See Also

moneypunct class template, moneypunct_byname class template

money_get 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-27 shows a simple use of money_get and money_put.

Example

Example 13-27. Reading and writing monetary values
#include <iostream>
#include <locale>
#include <ostream>
   
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. Imagine that for each virtual-function description, there is a corresponding description for a public, nonvirtual function, such as:

iter_type get(iter_type begin, iter_type end, bool intl, ios_base& stream, ios_base::iostate& err, long double& units) const

Calls do_get(begin, end, intl, stream, err, units)

The following are the virtual, protected members of money_get:

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

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>. 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'-'9'), in which each character c is produced by calling ctype<char_type>.widen(c).

If a valid sequence is not found, 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.

If the showbase flag is set (stream.flags( ) & stream.showbase is not 0), the currency symbol is required; otherwise, it is optional. Thousands grouping, if the local format supports it, is optional.

The sign of the result is dictated by positive_sign( ) and negative_sign( ) from the moneypunct facet.

The return value is an iterator that points to one past the last character of the monetary value.

See Also

money_put class template, moneypunct class template, num_get class template

money_put 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-27 (under money_get), which shows how to use 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. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

iter_type put(iter_type iter, bool intl, ios_base& stream, char_type fill, long double units) const

Returns do_put(iter, intl, stream, fill, units)

The following are the virtual, protected members of money_put:

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

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.

The formatting pattern and punctuation characters are obtained from the moneypunct facet. For positive values, 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 nonzero). Thousands separators and a decimal point are inserted at the appropriate places in the formatted output.

If necessary, fill characters are inserted until the formatted width is stream.width( ). The stream's adjustfield flag dictates how fill characters are inserted. That is, stream.flags( ) & stream.adjustfield is tested, and if it is equal to:

ios_base::internal

Fill characters are inserted where the pattern is none or space.

ios_base::left

Fill characters are appended to the end of the formatted field.

None of the above

Fill characters are inserted at the start of the formatted field.

Finally, stream.width(0) is called to reset the field width to 0. The return value is an iterator that points to one past the last output character.

See Also

money_get class template, moneypunct class template, num_put class template

moneypunct 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.

Specify true for the International template parameter to obtain an international format, or false to obtain a local format. In an international format, the currency symbol is always four characters, 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, in which 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. Imagine that for each virtual-function description, there is a corresponding description for a public, nonvirtual function, such as:

string_type curr_symbol( ) const

Returns do_curr_symbol( )

The following are the virtual, protected members of moneypunct:

virtual string_type do_curr_symbol( ) const

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

Returns the character used before the fractional part when do_frac_digits is greater than 0. For example, in the U.S., this is typically '.', and in Europe, it is typically ','. In the "C" locale, the decimal point is '.' or L'.'.

virtual int do_frac_digits( ) const

Returns the number of digits to print after the decimal point. This value can be 0. In the "C" locale, the number of digits is std::numeric_limits<char>.max( ).

virtual string do_grouping( ) const

Returns a string that specifies the positions of thousands separators. The string is interpreted as a vector of integers, in which each value is a number of digits, starting from the right. Thus, the string "\3" means every three digits form a group. In the "C" locale, the grouping is "" or L"".

virtual pattern do_neg_format( ) const

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

Returns the string (which may be empty) used to identify 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

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

Returns the string (which may be empty) used to identify 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

Returns the character used to separate groups of digits, in which 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 '\0' or L'\0'.

See Also

money_base class, money_get class template, money_put class template, moneypunct_byname class template, numpunct class template

moneypunct_byname 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.

See Also

moneypunct class template

num_get 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. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

iter_type get(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, bool& v) const

Returns do_get(begin, end, stream, err, v)

The following are the virtual, protected members of num_get:

virtual iter_type do_get(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, bool& v) const

Reads a bool value, which can be represented as a number or as a character string. The function first tests the boolalpha flag, that is, stream.flags( ) & stream.boolalpha. If the flag is 0, a numeric value is read; if the flag is 1, a string is read from [begin, end).

If boolalpha is false, the input is interpreted as a long int. If the numeric 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.

If boolalpha is true, characters are read from begin until one of the following happens:

  • The input matches truename( ) from the numpunct facet:

    use_facet<numpunct<char_type> >(stream.getloc(  )).truename(  )

    v is assigned true, and err is assigned goodbit. A match is determined by the shortest input sequence that uniquely matches truename( ) or falsename( ).

  • The input matches falsename( ): v is assigned false, and err is assigned goodbit.

  • begin == end, in which case eofbit is set in err.

  • The input does not match 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

Reads a single value. The do_get function is overloaded for most of the fundamental types. The behavior of each function is essentially the same (except for the bool version described earlier) and depends on stream.flags( ), the ctype facet, and the numpunct facet. Both facets are obtained for the locale stream.getloc( ).

First, input characters are collected from the range [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 it is oct, only octal characters are read ('0'-'7'). If the basefield is 0, the prefix determines the radix: 0x or 0X for hexadecimal, 0 for octal, and anything else for decimal. Floating-point numbers can use fixed or exponential notation, regardless of the flags.

figs/acorn.gif

If v is of type void*, the format is implementation-defined in the same manner as the %p format for scanf (in <cstdio>).

After all the valid characters have been read, they are interpreted as a numeric value. If the string is invalid, or if the thousands groupings are incorrect, 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.

See Also

money_get class template, num_put class template, numpunct class template, basic_istream in <istream>

num_put class template 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. Imagine that for each virtual function description, there is a corresponding description for a public, nonvirtual function, such as:

iter_type put(iter_type out, ios_base& stream, char_type fill, bool v) const

Returns do_put(out, stream, fill, v)

The following are the virtual, protected members of num_put:

virtual iter_type do_put(iter_type out, ios_base& stream, char_type fill, bool v) const

Writes a bool value to out. If the boolalpha flag is clear, that is, stream.flags( ) & stream.boolalpha is 0, the integer value of v is written as a number. If boolalpha is set, v is written as a word: if v is true, truename( ) is written; if v is false, falsename( ) is written using the numpunct facet. For example:

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

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:

Integral types (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'-'f' for the digits 10-16, or 'A'-'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).

Floating-point types (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.

If the floatfield flags do not indicate fixed or scientific, the general format is used: exponential if the exponent is -4 or less or greater than the precision (number of places after the decimal point), or fixed otherwise. Trailing zeros are dropped, as is the decimal point if would be the last character in the string.

If the uppercase flag is set, the exponent is introduced by 'E', or else by 'e'. If the showpoint flag is set, the decimal point is always present.

figs/acorn.gifPointer (void*)

The output format for a pointer is implementation-defined.

If the number is negative, it is prefaced with a minus sign ('-'). If the number is positive, no sign is output unless the showpos flag is set, in which case a positive sign ('+') appears at the start of the string.

If a decimal point character is needed, it is obtained from the numpunct facet's decimal_point( ) function. Integers have thousands separators inserted according to the grouping( ) function. See numpunct later in this section for more information.

If necessary, fill characters are inserted until the formatted width is stream.width( ). The stream's adjustfield flag dictates how fill characters are inserted. That is, stream.flags( ) & stream.adjustfield is tested, and if it is equal to:

ios_base::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.

ios_base::left

Fill characters are appended to the end of the formatted field.

Any other value

Fill characters are inserted at the start of the formatted field.

Finally, stream.width(0) is called to reset the field width to 0. The return value is an iterator that points to one past the last output character.

See Also

money_put class template, num_get class template, numpunct class template, basic_ostream in <ostream>

numpunct class template 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. Imagine that for each virtual-function description, there is a corresponding description for a public, nonvirtual function, such as:

char_type decimal_point( ) const

Returns do_decimal_point( )

The following are the virtual, protected members of numpunct:

virtual char_type do_decimal_point( ) const

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

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

Returns a string that specifies the positions of thousands separators. The string is interpreted as a vector of integers, in which each value is a number of digits, starting from the right. Thus, the string "\3" means every three digits form a group. In the "C" locale, the grouping is "" or L"".

virtual char_type do_thousands_sep( ) const

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 typically '.'. In the "C" locale, the thousands separator is '\0' or L'\0'.

virtual string_type do_truename( ) const

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".

See Also

moneypunct class template, num_get class template, num_put class template

numpunct_byname 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 template is a facet for numeric formatting and punctuation; it uses the rules of a named locale. The numpunct_byname<char> and numpunct_byname<wchar_t> instantiations are standard.

See Also

numpunct class template

time_base class 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.

See Also

time_get class template

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 in much the same way other facets and their functions do. Unlike other facets, however, 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.

Most of the time_get functions take a t parameter, which is a pointer to a tm object, which is filled in with the relevant parts of the date and time. If a function fails, the state of the tm object 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. Imagine that for each virtual-function description, there is a corresponding description for a public, nonvirtual function, such as:

dateorder date_order( ) const

Returns do_date_order( )

The following are the virtual, protected members of time_get:

virtual dateorder do_date_order( ) const

Returns the order in which the day, month, and year appear 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.

figs/acorn.gifvirtual iter_type do_get_time(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, tm* t) const

Reads characters from [begin, 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 stopped.

virtual iter_type do_get_date(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, tm* t) const

Reads characters from [begin, 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 stopped.

virtual iter_type do_get_weekday(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, tm* t) const

Reads characters from [begin, end) until it reads the name of a day of the week, either abbreviated or spelled out. 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 stopped.

virtual iter_type do_get_monthname(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, tm* t) const

Reads characters from [begin, end) until it reads the name of a month, either abbreviated or spelled out. 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 stopped.

virtual iter_type do_get_year(iter_type begin, iter_type end, ios_base& stream, ios_base::iostate& err, tm* t) const

Reads characters from [begin, end) until it reads a year. It is up to the implementation to determine whether two-digit years are accepted, and if so, which century to apply to the abbreviated year. The 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 stopped.

See Also

time_base class, time_get_byname class template, time_put class template, tm in <ctime>

time_get_byname class template 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.

See Also

time_get class template

time_put 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. Here are the complete descriptions of put and do_put:

iter_type put(iter_type out, ios_base& stream, char_type fill, const tm* t, const charT* pattern, const charT* pat_end) const

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. A format specifier starts with '%' and is followed by an optional modifier character, which is followed in turn by a format specifier character. The put function checks format characters by first calling narrow from the ctype<charT> facet, then checking the narrowed character.

For each format specifier, put calls do_put(out, stream, fill, t, format, modifier), in which format is the format specifier and modifier is the modifier character or 0 if no modifier is present.

figs/acorn.gif

The use of modifier characters is implementation-defined. The standard does not define any modifiers. See the do_put member function for more information.

iter_type put(iter_type out, ios_base& stream, char_type fill, const tm* t, char format, char modifier = 0) const

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

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-22). The date and time information is obtained from t.

The do_put function, unlike some of the other output facets, does not use stream's flags or field width. The fill parameter is used by implementation-defined formatting.

Table 13-22. Format specifiers for do_put

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

A.M./P.M. designation for use with a 12-hour clock

S

Second (00-61); up to two 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 %

figs/acorn.gif

The use of 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 unmodified format specifier.

See Also

time_get class template, time_put_byname class template, <ctime>

time_put_byname class template 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.

See Also

time_put class template

tolower function template Converts 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:

use_facet<ctype<charT> >(loc).tolower(c)

See Also

ctype class template, islower function template, toupper function template

toupper function template Converts 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:

use_facet<ctype<charT> >(loc).toupper(c)

See Also

ctype class template, isupper function template, tolower function template

use_facet function template Retrieves 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 Example 13-24 and Example 13-27, earlier in this section.

See Also

has_facet function template, locale::facet class

    Team LiB   Previous Section   Next Section