zoukankan      html  css  js  c++  java
  • C++ TCHAR* 与char* 互转

    C++ TCHAR* 与char* 互转

    在MSDN中有这么一段:

    Note: The ANSI code pages can be different on different computers, or can be changed for a single computer, leading to data corruption. For the most consistent results, applications should use Unicode, such as UTF-8 (code page 65001) or UTF-16, instead of a specific code page, unless legacy standards or data formats prevent the use of Unicode. If use of Unicode is not possible, applications should tag the data stream with the appropriate encoding name when protocols allow it. HTML, XML, and HTTP files allow tagging, but text files do not.

    大概意思就是说ANSI页码的文件可能会根据不同的计算机而改变,建议使用unicode(UTF-8或UTF-16)的编码

    而VS默认就使用unicode编码

    ANSI:char, string …

    UNICODE: TCHAR, wchar_t …

    MSDN里给我们提花了两个函数

    MultiByteToWideChar

    int MultiByteToWideChar(
    
    UINT CodePage,
    
    DWORD dwFlags,
    
    LPCSTR lpMultiByteStr,
    
    int cbMultiByte,
    
    LPWSTR lpWideCharStr,
    
    int cchWideChar
    
    );

    WideCharToMultiByte:

    int WideCharToMultiByte(
    
    UINT CodePage,
    
    DWORD dwFlags, 
    
    LPCWSTR lpWideCharStr,
    
    int cchWideChar,
    
    LPSTR lpMultiByteStr, 
    
    int cbMultiByte,
    
    LPCSTR lpDefaultChar,
    
    LPBOOL lpUsedDefaultChar
    
    );

    互转的实现:

    char* StrUtils::TCHAR2char( const TCHAR* STR )
    
    {
    
    //返回字符串的长度
    
    int size = WideCharToMultiByte(CP_ACP, 0, STR, -1, NULL, 0, NULL, FALSE);
    
    //申请一个多字节的字符串变量
    
    char* str = new char[sizeof(char) * size];
    
    //将STR转成str
    
    WideCharToMultiByte(CP_ACP, 0, STR, -1, str, size, NULL, FALSE);
    
    return str;
    
    }
    
    TCHAR* StrUtils::char2TCAHR( const char* str )
    
    {
    
    int size = MultiByteToWideChar(CP_ACP, 0, str, -1, NULL, 0);
    
    TCHAR* retStr = new TCHAR[size * sizeof(TCHAR)];
    
    MultiByteToWideChar(CP_ACP, 0, str, -1, retStr, size);
    
    return retStr;
    
    }
  • 相关阅读:
    CF 118E Bertown roads 桥
    hdu 3917 Road constructions 最大权闭合子图
    hdu 4714 Tree2cycle 树形经典问题
    POJ 2516 Minimum Cost 最小费用流
    POJ 3921 Destroying the bus stations 沿着最短路迭代加深搜索
    POJ 3422 Kaka's Matrix Travels K取方格数
    BZOJ 3083: 遥远的国度 dfs序,树链剖分,倍增
    hdu 4010 Query on The Trees LCT
    poj 2455 Secret Milking Machine 二分+最大流 sap
    定制标记---简单标记处理器
  • 原文地址:https://www.cnblogs.com/imzhstar/p/4107558.html
Copyright © 2011-2022 走看看