clocale header file in C++

C++Server Side ProgrammingProgramming

Given the task is to show the use of <clocale> header file in C++.

The <clocale> header file is a part of the localization library which further is a part of the C++ standard library. Originally it was in the C standard library with the name as <locale.h>.

The functions and declarations included in this header file are used for tasks that require date formats and currency symbols of different countries.

The functions included in <clocale> header file are setlocale() and localeconv()

The macros that are defined in this header file and are used in these two functions are −

LC_ALL-> It sets everything.

LC_COLLATE-> It affects strcoll and strxfrm functions.

LC_CTYPE-> It affects all character functions.

LC_MONETARY-> It affects the monetary information provided by localeconv function.

LC_NUMERIC-> It affects decimal-point formatting and the information provided by localeconv function.

LC_TIME-> It affects the strftime function.

localeconv()

The localeconv() function sets or reads the information that is location dependent.

Syntax

The syntax for localeconv() is as follows −

Struct lconv*localeconv()

setlocale()

The setlocale() function installs the specified system locale and sets the locale information as per the current program.

Syntax

The syntax for setlocale() is as follows

char *setlocale(int category, const char *locale)

Example

Input: setlocale(LC_ALL, "en_GB")
s = setlocale(LC_ALL, NULL)
Output: C

setlocale() returns a pointer to the string, if it identifies it will return the C locale otherwise it just returns a null pointer and in this case it returns “C”.

Approach used in the below program as follows

• First call setlocale() function inside the main() function and set the category as LC_MONETARY and the locale as en_GB.
• Then create the structure lconv with char pointer, let’s say, lc and keep it equal to the calling of the localeconv() function so that the localeconv() function can return a pointer to the structure that we have created.
• The use the printf statement to print the current currency.

Example

Live Demo

#include <iostream>
#include <locale.h>
using namespace std;
int main() {
setlocale(LC_MONETARY, "en_GB");
struct lconv* lc = localeconv();
printf("%s ", lc->currency_symbol);
return 0;
}

Output

If we run the above code it will generate the following output −

£

In the output we get the currency symbol of pound which is the currency of Great Britain because in the setlocale function we selected the monetary category that is LC_MONETARY and set the locale as "en_GB" where GB is the abbreviation for Great Britain. Further we created the lconv structure and used it for displaying the current currency symbol of Great Britain, that is £.

Published on 20-Jan-2020 07:33:16
Advertisements