How to use wctomb() in C++

The wctomb function converts a wide character to a multi-byte character. To use the wctomb function, the cstdlib header file needs to be included in the program, as shown below:

#include <cstdlib>

Prototype

The prototype of the wctomb() function is as follows:

int wctomb(char* pointerMb, wchar_t wc);

The function takes two arguments and returns an integer value. It stores the return value at the memory location that is pointed by pointerMb and stores a maximum of MB_CUR_MAX characters.

Parameters

It takes two values as arguments:

  1. pointerMb: pointer to the resulting multi-byte character

  2. wc: wide character

Return value

It returns different values based on whether pointerMb is Null or not. The return values are represented in the figure below:

Figure 1. Different return values of wctomb under different conditions

Example 1

The following code explains the use of the wctomb function in C++ when the value of pointerMb is NULL:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
wchar_t wc_valid = L'x';
char *pointerMb = NULL;
int returnValue;
returnValue = wctomb(pointerMb, wc_valid);
cout << "PointerMb = NULL:" << endl;
cout << "Return Value: " << returnValue << endl;
return 0;
}

Example 2

The following code explains the use of the wctomb function in C++ when the value of pointerMb is not NULL:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
wchar_t wc_valid = L'x';
char *pointerMb = (char*)malloc(sizeof(char));
int returnValue;
returnValue = wctomb(pointerMb, wc_valid);
cout << "PointerMb != NULL and wc = valid:" << endl;
cout << "Return Value: " << returnValue << endl;
return 0;
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved