C++ wctob()

The wctob() function in C++ converts a wide character to a single byte character (of type char) if its multibyte character equivalent is a single byte.

The wctob() function is defined in <cwchar> header file.

wctob() prototype

int wctob( wint_t c );

The wctob() function takes a wide character c as its argument and returns its narrow single byte character equivalent if possible.


wctob() Parameters

  • c: The wide character to narrow.

wctob() Return value

If c represent a multibyte character of length 1 in initial shift state, the wctob() function returns the single byte representation of c. Otherwise EOF is returned.


Example: How wctob() function works?

#include <cwchar>
#include <clocale>
#include <iostream>
#include <cstdio>
using namespace std;

void test_wctob(wchar_t c)
{
	int ch = wctob(c);
	if (ch != EOF)
		wcout << c << L" can be narrowed" << endl;
	else
		wcout << c << L" can't be narrowed" << endl;
}

int main()
{
	setlocale(LC_ALL, "en_US.utf8");

	wchar_t wc1 = L'm';
	wchar_t wc2 = L'\u00c6';
	
	test_wctob(wc1);
	test_wctob(wc2);
	
	return 0;
}

When you run the program, the output will be:

m can be narrowed
Æ can't be narrowed
Did you find this article helpful?