What is towupper() in C++?

The towupper() function is a built-in function of C++. It helps convert wide characters to uppercase characters.

A wide character is like a normal character data type, except it represents the unicode character set instead of the ASCII character set. Hence, a wide character takes up 2-bytes of space as compared to the 1-byte taken by a normal character.

In order to represent an ASCII string as a wide character or string, “L” is used by attaching it to the beginning of the string. For example, L"Hello world!".

To use towupper() in C++, you must include the cwctype.h header file.

#include <cwctype.h>

Syntax

wint_t towupper( wint_t ch );

Parameter

The towupper() function takes a wide character as a parameter.

  • ch: This is the wide character that is passed in order to be converted to uppercase.

Return value

The function returns two values.

  • If the ch has an uppercase version, then it is converted.
  • If the ch does not have an uppercase version, then no modification happens.

Code

In the code below, we create some wide characters and convert them to uppercase.

#include <cwctype>
#include <iostream>
using namespace std;
int main() {
wchar_t a = L'S'; // Not a wide character
wchar_t b = L'C'; // Not a wide character
wchar_t c = L'S'; // A wide character but not lowercase
wchar_t d = L'c'; // A wide character and lowercase too
putwchar(towupper(a));
putwchar(towupper(b));
putwchar(towupper(c));
putwchar(towupper(d));
return 0;
}

Example

In the example below, we will create an array of wide characters, convert them to upper case, and print them to the console.

#include <cwchar>
#include <cwctype>
#include <iostream>
using namespace std;
int main()
{
wchar_t str[] = L"edpresson is awesome|!";
wcout << L"The uppercase version of \"" << str << L"\" is ";
for (int i = 0; i < wcslen(str); i++)
// Function to convert the character
// into the uppercase version, if exists
putwchar(towupper(str[i]));
return 0;
}

Free Resources