Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is wcstombs() in C?

Syed Muhammad Ali Mustafa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

We can use the wcstombs() function to convert a wide-character string to its equivalent multibyte sequence of characters. We can do this until we convert the maximum number of bytes or encounter a NULL character.

Library

The wcstombs() function is defined in the following library:

#include<stdlib.h>

Declaration

Below is the declaration of the wcstombs() function:

size_t wcstombs (char* destination, const wchar_t* source, size_t maximum);

Parameters

  • destination: The pointer to a char array at least maximum bytes long.
  • source: The pointer to the wide-character string that will be translated.
  • maximum: An unsigned integral thst specifies the maximum number of bytes that will be translated.

Return value

Upon successful conversion, the function returns the number of bytes written into destination, excluding the null character. In case of any error, the function returns -1.

Code

The code below explains the use of wcstombs() function.

#include <stdio.h>
#include <stdlib.h>
int main() {
wchar_t src[] = L"I love Educative <3";
char dest[64];
int returnValue;
returnValue = wcstombs(dest, src, sizeof(dest));
printf("Wide-character string: %ls\n", src);
printf("Multibyte string: %s\n", dest);
printf("Number of bytes converted: %d\n", returnValue);
return 0;
}

Explanation

In line 5-7, a wide-character string is initialized and a character string and an integer are declared. Then, in line 9, the function is called with the necessary parameters. The subsequent lines show the output.

RELATED TAGS

c

CONTRIBUTOR

Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring