CodeBlanks Logo Icon CodeBlanks

Summary - Unicode

Combine UTF-8 and wchar_t to write a multilingual hello app.

Summary - Unicode

In this group you learned the ASCII/UTF-8 difference, wchar_t, setlocale, mbstowcs and a UTF-8 decoder. Now you'll combine everything into a multilingual hello app.

The program prints an ASCII string, sets the locale to "C", computes the byte count with strlen and the wide character count with mbstowcs, and prints all three. All outputs are deterministic: for "Merhaba" bytes are 7 and wide characters are 7.

Practice Multilingual hello

Declare const char *s = "Merhaba";. Print it with printf("%s\n", s);. Call setlocale(LC_ALL, "C");. Compute size_t mb = strlen(s); and size_t wcs = mbstowcs(NULL, s, 0);. Print printf("bayt: %zu\n", mb); and printf("wcs: %zu\n", wcs);.

Starter code

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

// Print "Merhaba", set locale to 'C'
// Print strlen byte count and mbstowcs wide count

int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <locale.h>

int main(void) {
    const char *s = "Merhaba";
    printf("%s\n", s);
    setlocale(LC_ALL, "C");
    size_t mb = strlen(s);
    size_t wcs = mbstowcs(NULL, s, 0);
    printf("bayt: %zu\n", mb);
    printf("wcs: %zu\n", wcs);
    return 0;
}

Expected output

Merhaba
bayt: 7
wcs: 7

Next steps

You learned the foundation of Unicode and i18n. ASCII is one byte, UTF-8 is variable, wchar_t holds wide characters. You set the locale with setlocale; you convert both ways with mbstowcs and wcstombs.

Next steps: restartable conversion with mbrtowc, full Unicode support with the ICU library, and fixed-width code point storage with char32_t. You can extend your UTF-8 decoder to three and four byte sequences.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which function must be called before multibyte conversion?

  • printf
  • setlocale Correct answer
  • strlen
  • malloc

Explanation: Without setlocale mbstowcs behavior is undefined.

2 Match functions to purpose

Term Meaning
strlen Counts bytes
mbstowcs Wide string
setlocale Sets locale
decode_utf8 Code point

All lessons in Advanced