C++ Standard Library C++ STL Library

C++ <cwchar> - mbstate_t Type



The C++ mbstate_t type is a trivial non-array type that stores the conversion state used to convert between multibyte characters and wide characters (either way). This type is implementation-defined and it can represent any of the conversion states. Zero-initialized value of mbstate_t represents the initial conversion state, although other values of mbstate_t may exist that also represent the initial conversion state.

The initial state is the state at the beginning of conversion of a string. There are two kinds of state: the one used by multibyte to wide character conversion functions, such as mbrtowc() function, and the one used by wide character to multibyte conversion functions, such as wcrtomb() function, but they both fit in an mbstate_t, and they both have the same representation for an initial state.

If two mbstate_t objects are identical, they represent the same shift state, but the reverse is not necessarily true.

The state pointed by an mbstate_t object mbs can be set to the initial state by calling memset() function as given below:

memset(&mbs, 0, sizeof(mbs));              

There is no way to compare two mbstate_t objects to determine whether they represent the same state, but mbsinit() function can be called to determine whether a state is the initial state.

Example:

The example below illustrates on mbstate_t type.

#include <cstdio>
#include <cstring>
#include <cwchar>
 
int main (){
  char buff[50];
  mbstate_t mbs;
  wchar_t wcs[] = L"mbstate_t Example";
  const wchar_t* ptr;

  ptr = wcs;

  //setting to initial state
  if (!mbsinit(&mbs))
    memset (&mbs,0,sizeof(mbs));  

  wcsrtombs(buff, &ptr, 50, &mbs);
  printf("%s", buff);
 
  return 0;
}

The output of the above code will be:

mbstate_t Example

❮ C++ <cwchar> Library