C++ c32rtomb()

The c32rtomb() function in C++ converts a 32 bit character to representation to a narrow multibyte character representation.

The c32rtomb() function is defined in <cuchar> header file.

c32rtomb() prototype

size_t c32rtomb(char* s, char32_t c32, mbstate_t* ps);

The c32rtomb() function converts the utf-32 character c32 to its multibyte equivalent and store it in the object pointed to by s.

If s represents a null pointer, the call is equivalent to c32rtomb(buf, U'\0', ps) for some internal buffer buf.

If c32 is the null wide character i.e. U'\0', a null byte is stored.

c32rtomb() Parameters

  • s: Pointer to a character array where the multibyte character is stored.
  • c32: The 32 bit character to convert.
  • ps: A pointer to an mbstate_t object used when interpreting the multibyte string.

c32rtomb() Return value

  • On success, the c32rtomb() function returns the number of bytes written to the character array pointed to by s.
  • On failure, -1 is returned and errno is set to EILSEQ.

Example: How c32rtomb() function works?

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

int main()
{
	const char32_t str[] = U"C++ is super fast.";
	char s[50];
	mbstate_t ps{};
	size_t length;
	int j = 0;

	while (str[j])
	{
		length = c32rtomb(s, str[j], &ps);
		if ((length == 0) || (length > 50))
			break;

		for (int i=0; i<length; ++i)
			cout << s[i];
		++j;
	}

	return 0;
}

When you run the program, the output will be:

C++ is super fast.