Wctob Function In C++

The wctob function in C++ is used to translate a wide character into an equivalent single-byte character representation. It is a component of the <cwchar> header. It is usually applied to multibyte character encodings.

Syntax:

It has the following syntax:

Example

int wctob(wint_t wc);

Parameters:

wc: You wish to convert this wide character of type wint_t .

Return Value:

  • The function returns the corresponding single-byte character representation for a wide character (wc) that can be represented as an unsigned char cast to an int.
  • The function returns EOF if and only if wc is the wide character representation of an invalid single-byte character or WEOF (end-of-file wide character) .
  • Description:

  • The wctob function is commonly used in the context of multibyte character encodings because not all wide characters can be represented as single-byte characters.
  • It determines if a single-byte character is represented for a given wide character (WCC) .
  • If so, an integer representing the single-byte character representation is returned. It returns EOF if it doesn't or if wc is WEOF to indicate an error or end-of-file.
  • Example 1:

Let's take an example to illustrate the use of the wctob function in C++.

Example

#include <cwchar>
#include <iostream>
int main() {
wchar_t wideChar = L'A';
int result = wctob(wideChar);
if (result != EOF) {
std::cout << "Corresponding single-byte character: " << static_cast<char>(result) << std::endl;
} else {
std::cerr << "Invalid wide character or end-of-file." << std::endl;
}
return 0;
}

Output:

Explanation:

  • This example will print the corresponding single-byte character if wideChar is a wide character with a valid single-byte character representation. It will print an error message.
  • Remember that the wctob function works best when combined with other wide character functions, and that the program's particular locale and encoding settings may affect how the function behaves.
  • Example 2:

Let's take another example to illustrate the use of the wctob function in C++.

Example

#include <bits/stdc++.h> 
int fun() 
{ 
int i, num; 
const wchar_t wc[] = L"priya lal"; 
num = 0; 
for (i = 0; i < wcslen(wc); ++i) 
if (wctob(wc[i]) != EOF) 
++num; 
wprintf(L"wc has %d characters to be translated"
			"to single-byte characters.", num); 
} 
int main() 
{ 
fun(); 
return 0; 
}

Output:

Example 3:

Let's take another example to illustrate the use of the wctob function in C++.

Example

#include <bits/stdc++.h> 
void fun(wchar_t wc) 
{ 
int cn = wctob(wc); 
if (cn != EOF) 
printf("%#x translated to %#x\n", wc, cn); 
else
printf("%#x could not be translated\n", wc); 
} 
int main(void) 
{ 
char* utf_locale_present = setlocale(LC_ALL, "th_TH.utf8"); 
puts("In Thai UTF-8 locale:"); 
fun(L'a'); 
fun(L'?'); 
}

Output:

Input Required

This code uses input(). Please provide values below: