gcc c++ wcout/cout printf/wprintf 中文输出问题

#include <stdio.h>
#include <clocale>
#include <windows.h>
#include <string>
#include <iostream>

using namespace std;


//编译连接加上 -fexec-charset=gbk -finput-charset=gbk 

const char* psa = "A汉字ABC";
const wchar_t* psw = L"W汉字ABC";

string UnicodeToANSI(const wstring& str)
{
    char *pStr;
    int iwstrLen = WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, 0, 0, 0, 0);
    cout << "iwstrlen=" << iwstrLen << endl;
    pStr = new char[iwstrLen +1];
    memset(pStr, 0, sizeof(char)*(iwstrLen + 1));
    WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, pStr, iwstrLen, 0, 0);
    string strText;
    strText = pStr;
    delete pStr;
    cout << "转换ANSI完成" << endl;
    return strText;
}

wstring ANSItoUnicode(const string& str)
{
    wchar_t *pwstr;
    int istrLen = MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, 0, 0);
    cout << "istrlen=" << istrLen << endl;
    pwstr = new wchar_t[istrLen + 1]{0};
    memset(pwstr, 0, (istrLen + 1) * sizeof(WCHAR));
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, pwstr, istrLen);
    wstring wTemp = pwstr;
    delete pwstr;
    cout << "转换Unicode完成" << endl;
    return wTemp;
}

int main(int argc, char* argv[])
{
    ios::sync_with_stdio(false);    // Linux gcc.
   // locale::global(locale(""));
    wcout.imbue(locale(""));
    setlocale(LC_CTYPE, "");       // MinGW gcc.
   // wcout.imbue(locale(locale(), "", LC_CTYPE));


    // C++
    cout <<"C++:\n"<< endl;
    cout << psa << endl;
    wcout << psw << endl;
    wcout << 12345 << endl;
    
    wstring str = ANSItoUnicode(psa);
    wcout << str.length() << endl << str << endl;

    string str1 = UnicodeToANSI(psw);
    cout << str1.length() << endl << str1 << endl;

    // C
    printf("\n\nC:\n");
    printf("\t%s\n", psa);
    printf("\t%ls\n", psw);
    wprintf(L"\t%s\n", psw);


    return 0;
}
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值