M
M
MayRiv2016-08-26 12:05:22
linux
MayRiv, 2016-08-26 12:05:22

How to convert UTF-8 to Windows-1251 with iconv transliteration?

I am not able to convert the string "aÜ" with transliteration using the plus program, the resulting string is "a?", and the desired one is "aU"
Whereas when I use the php script on the same machine, "<?php echo iconv("UTF-8", "Windows-1251//TRANSLIT", "Ü");>", everything works fine.
What could be causing the error?
Program text:

#include <cstdlib>
#include <iconv.h>
#include <locale.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
using namespace std;

int IConvert(char *buf, size_t len, const char *from, const char *to)
{
  iconv_t iconv_cd;
  if ((iconv_cd = iconv_open(to, from)) == (iconv_t) -1) {
    printf("Cannot open iconv from %s to %s\n", from, to);
    return 0;
  }

  char *inbuf = buf;
  char *outbuf = buf;
  size_t inlen = len;
  size_t outlen = len;
  size_t res = 0;

  while (inlen > 0 && outlen > 0) {
    res = iconv(iconv_cd, &inbuf, &inlen, &outbuf, &outlen);
    if (res == 0)
      break;

    if (res == (size_t) (-1)) {
      if (errno != EILSEQ && errno != EINVAL) {
        iconv_close(iconv_cd);
        *outbuf = '\0';
        printf("Erorr %s (%s)\n", strerror(errno), from);

        return 0;
      } else if (inbuf < outbuf) {
        iconv_close(iconv_cd);
        *outbuf = '\0';
        printf("Erorr %s (inbuf < outbuf)\n", strerror(errno));

        return 0;
      }
    }
    if (inlen > 0 && outlen > 0) {
      *outbuf++ = *inbuf++;
      inlen--;
      outlen--;
    }
  }
  iconv_close(iconv_cd);
  *outbuf = '\0';
  return 1;
}
int main(int argc, char** argv) {
        char* from = "aÜ";
        char* to = (char*) malloc(strlen(from)+1);
        strcpy(to, from);
        IConvert(to, strlen(from)+1, "UTF-8", "CP1251//TRANSLIT");
        
        printf("%s\n", to);
    return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
MayRiv, 2016-08-26
@MayRiv


They suggested on stackoverflow, the setlocale(LC_ALL, ""); function completely solves the problem . at the beginning of the program.
Why - I'll still google.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question