简体   繁体   中英

How do I use system("chcp 936") in my dialog based project?

The code below is supposed to convert a wstring "!" to a string and output it,

    setlocale(LC_ALL, "Chinese_China.936");
    //system("chcp 936"); 
    
    std::wstring ws = L"!";
    string as((ws.length()) * sizeof(wchar_t), '-');
    auto rs = wcstombs((char*)as.c_str(), ws.c_str(), as.length());
    as.resize(rs);
    cout << rs << ":" << as << endl;

If you run it without system("chcp 936"); , the converted string is "£¡" rather than "!". If with system("chcp 936"); , the result is correct in a console project.

在此处输入图像描述

But on my Dialog based project, system("chcp 936") is useless, even if it's workable, I can't use it, because it would popup a console.

在此处输入图像描述

PS: the IDE is Visual Studio 2019, and my source code is stored as in UTF-8 with signature. My operation system language is English and language for non-unicode programs is English (United States).

在此处输入图像描述

Edit: it's interesting, even with "en-US" locale, "!" can be converted to an ASCII ".".

在此处输入图像描述

But I don't get where "£¡" I got in the dialog based project.

There are two distinct points to considere with locales:

  • you must tell the program what charset should be used when converting unicode characters to plain bytes (this is the role for setlocale )
  • you must tell the terminal what charset it should render (this is the role for chcp in Windows console)

The first point depends on the language and optionaly libraries that you use in your program (here the C++ language and Standard Library)

The second point depends on the console application and underlying system. Windows console uses chcp , and you will find in that other post how you can configure xterm in a Unix-like system.

I found out the cause, the wstring-to-string conversion is no problem, the problem was I used CA2T to convert the Chinese punctuation mark and it failed. So it showed "£¡" in the UI finally.

By means of mbstowcs , the counterpart of wcstombs , it would work.

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM