C++ <cstdlib> - mblen() Function
The C++ <cstdlib> mblen() function returns the size (in bytes) of the multibyte character whose first byte is pointed to by str and examining at most n bytes.
This function has its own internal shift state, which is altered as necessary only by calling it. If str is a null pointer, it resets its internal conversion state to represent the initial shift state and returns whether multibyte encoding is state-dependent.
Syntax
int mblen(const char *str, size_t n)
Parameters
str |
Specify pointer to the multibyte character. |
n |
Specify maximum number of bytes in str that can be examined. size_t is an unsigned integral type. |
Return Value
When str is not a null pointer, it returns the number of bytes that are contained in the multibyte character or -1 if the first bytes pointed to by str do not form a valid multibyte character or 0 if str is pointing at the null charcter '\0'.
When str is a null pointer, it returns 0 if the current multibyte encoding is not state-dependent or a non-zero value if the current multibyte encoding is state-dependent.
Example:
In the example below, mblen() and mbtowc() functions are used in the user-defined function printbuffer(), which prints a multibyte string character by character.
#include <cstdio> #include <cstdlib> void printbuffer (char* str, size_t n){ int length; wchar_t dest; mblen (NULL, 0); //reset mblen mbtowc (NULL, NULL, 0); //reset mbtowc while (n > 0) { length = mblen(str, n); if (length < 1) break; mbtowc(&dest, str, length); printf("[%lc]", dest); str = str + length; n = n - length; } } int main (){ char str [] = "Hello World!"; printbuffer (str, sizeof(str)); return 0; }
The output of the above code will be:
[H][e][l][l][o][ ][W][o][r][l][d][!]
❮ C++ <cstdlib> Library