如何将国际字符发送到Windows控制台?

时间:2012-06-05 15:21:19

标签: c++ windows utf-8 console mingw

代码:

#include <windows.h>

int main() {
  SetConsoleOutputCP(CP_UTF8);
  system("echo Ιλιάδα");
}

在控制台上打印:Ιλιάδα 源以带有BOM的UTF-8编码。

但如果我尝试:system(L"echo Ιλιάδα");,我会收到错误:error: cannot convert 'const wchar_t*' to 'const char*' for argument '1' to 'int system(const char*)'。当然,我没想到其他任何事情。是否有其他功能可以接受这些字符?

3 个答案:

答案 0 :(得分:3)

使用_wsystem一个用于宽字符串。

答案 1 :(得分:0)

这是VC ++吗?

如果是这样,你的文件似乎是使用没有BOM的UTF-8,这意味着VC ++将假设源字符集和执行字符集是相同的,因此在生成字符串文字“echo”时它不会进行任何编码转换Ιλιάδα”。它将直接输出UTF-8数据。这意味着编译器认为您编写了system("echo Ιλιάδα");,其中垃圾是您的UTF-8字符串,就像它是系统的语言环境编码一样。

默认情况下,system()函数采用系统区域设置编码中的字符串。 控制台输出代码页对system()的操作没有影响,因此上面的字符串正是它所看到的。


因为您使用的是没有BOM的UTF-8,所以您会遇到宽字符串问题。生成宽字符串需要正确地将源字符集转换为广泛的执行字符集。如果您使用的是没有BOM的UTF-8,那么VC ++不知道正确的源编码,因此无法正确执行此转换。

答案 2 :(得分:0)

您可以尝试系统(“cmd / c lambdabath”)或系统(“lambdabath”),例如:

//Save As UTF-8 withput BOM signature

#include <stdlib.h>
#include <windows.h>

int main() {
    SetConsoleOutputCP(CP_UTF8);
    //system("cmd /c lambdabath");
    system("lambdabath");
}

lambdabath.bat(也保存为没有BOM签名的UTF-8):

chcp 65001
echo Ιλιάδα

但如果问题是:如何将国际字符发送到Windows控制台? 然后你可以尝试不同的编码。使用函数system()不是必需的。

Windows 1253 编码:

//Save As Windows 1253

 #include <stdio.h>
 #include <windows.h>

int main()
{
    SetConsoleOutputCP(1253);
    char *ansichar_ = "Ιλιάδα";
    unsigned char lambda1253char = 'λ';
    printf("ansichar_: %s\n", ansichar_);
    printf("λ %#x\n", lambda1253char);
}

结果:

ansichar_: Ιλιάδα
λ 0xeb

UTF-16 编码:

 //Save As UTF16 (Unicode)

    #include <stdio.h>
    #include <io.h>
    #include <fcntl.h>
    #include <wchar.h>

    int main()
    {
        _setmode(_fileno(stdout), _O_U16TEXT);
        wchar_t *wchar_ = L"Ιλιάδα";
        wchar_t lambdaWchar = L'λ';
        wprintf(L"wchar_: %s\n", wchar_);
        wprintf(L"λ %#x\n", lambdaWchar);
    }

结果:

wchar_: Ιλιάδα
λ 0x3bb

UTF-8 编码:

 //Save As UTF8 without BOM signature

    #include <stdio.h>
    #include <windows.h>

    int main()
    {
        SetConsoleOutputCP(65001);
        char *utf8char_ = "Ιλιάδα";
        int lambdaUTF8char = 'λ';
        printf("utf8char_: %s\n", utf8char_);
        printf("λ %#x\n", lambdaUTF8char);
    }

结果:

utf8char_: Ιλιάδα
λ 0xcebb

在任何情况下,请设置默认控制台字体:Lucida Console。

相关问题