C++ setlocale()

The setlocale() function in C++ sets the locale information for the current program.

The setlocale() function is defined in <clocale> header file.

setlocale() prototype

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

The setlocale function is used to set a specified system locale for the given category. The setlocale function can also be used to query the current C locale.

This can be done by passing a null pointer in place of locale.


setlocale() Parameters

  • category: Specifies which locale information of the program is affected. The possible macros for category are:
Category macro for setlocale()
Macros Description
LC_ALL Selects all the C locale
LC_COLLATE Selection the collation category
LC_CTYPE Selects the character classification category
LC_MONETARY Selects the monetary formatting category
LC_NUMERIC Selects the numeric formatting category
LC_TIME Selects the time formatting category
  • locale: A system specific locale identifier. If it is a null pointer, a call to setlocale() queries the current C locale.

setlocale() Return value

  • On success, the setlocale() function returns a pointer to the string identifying the C locale after applying the changes.
  • On failure it returns a null pointer.

Example: How setlocale() function works?

#include <clocale>
#include <iostream>
using namespace std;

int main()
{
	char *str;
	setlocale(LC_ALL, "en_US.utf8");
	
	str = setlocale(LC_ALL, NULL);
	cout << "Current locale: " << str << endl;
	cout << "Changing locale " << endl;
	
	setlocale(LC_ALL, "en_GB.utf8");
	str = setlocale(LC_ALL, NULL);
	wcout << "Current locale: " << str << endl;
	
	return 0;
}

When you run the program, the output will be:

Current locale: en_US.utf8
Changing locale
Current locale: en_GB.utf8