How to use mblen ()?

Here are some test codes to help me understand multi-byte character management.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]) {
    char * line = malloc(1024);
    size_t n;

    getline(&line, &n, stdin);
    while (*line) {
        int offset = mblen(line, strlen(line));
        if (offset == -1) return 0;
        printf("%d\n", offset);
        line += offset;
    }
    return 0;
}

As I understand it, if the user where to enter "éléphant", my output should show 2 1 2 1 ... However, it shows -1 for the mblen error, starting from the first byte. It doesn't seem to be a mistake in these two lines of code, what should I do, what resources can I read to get a hint of what is going on here? Of course, printf ("% s", string) will work (and works) perfectly.

+4
source share
1 answer

Turning my comment into a response.

Details may depend on your particular runtime, but I think the following should apply for most * NIX systems.

mblen depends on current locale

LC_CTYPE

- C (. setlocale), . setlocale(LC_CTYPE, ""), "" .

, setlocale(LC_ALL, "") ( ) , , , , .

+3

Source: https://habr.com/ru/post/1526397/


All Articles