验证码: 看不清楚,换一张 查询 注册会员,免验证
  • {{ basic.site_slogan }}
  • 打开微信扫一扫,
    您还可以在这里找到我们哟

    关注我们

C++ string和wstring怎么相互转换

阅读:408 来源:乙速云 作者:代码code

C++ string和wstring怎么相互转换

%S和%s用法

%s和%S都是格式化控制符,输出字符串类型。

但应用宽字符函数和窄字符函数却又一定的区别,我们针对printf函数以及wprintf函数进行说明:

针对窄字符函数,例如printf,sprintf函数而言:

  • %s 是指以窄字符方式输出字符串

  • %S 是指以宽字符方式输出字符串

针对宽字符函数,例如wprintf,swprintf函数而言,其作用恰恰相反:

  • %s 是指以宽字符方式输出字符串

  • %S 是指以窄字符方式输出字符串

总结起来就是%s是本身函数的字符类型,%S是本身函数类型的相反字符编码。

//输出窄字符
printf("ascii string=%sn","hello world");
//输出宽字符
printf("unicode string=%Sn",L"hello world");

//输出宽字符
wprintf(L"ascii string=%sn",L"hello world");
//输出窄字符
wprintf(L"unicode string=%Sn","hello world");

string和wstring转换方法

转换源码如下,需要说明的是这里不支持中文类型转换。

#include 
#include 
#include 

//wstring类型转换为string类型
std::string GetStringByWchar(const WCHAR* wszString)
{
     std::string strString; 
     if (wszString != NULL)
     {
         std::wstring ws(wszString);
         strString.assign(ws.begin(), ws.end());
     }

     return strString;
}

//string类型转换为wstring类型
std::wstring GetWStringByChar(const char* szString)
{
    std::wstring wstrString;
    if (szString != NULL)
    {
        std::string str(szString);
        wstrString.assign(str.begin(), str.end());
    }

    return wstrString; 
}

void Test()
{
    std::wstring wstrCHar = L"hell world";
    std::string strChar = "hell world";
    printf("ret string=%sn",GetStringByWchar(wstrCHar.c_str()).c_str());
    printf("ret wstring=%Sn",GetWStringByChar(strChar.c_str()).c_str());
    wprintf(L"ret wstring=%sn",GetWStringByChar(strChar.c_str()).c_str());
}

运行结果:

ret string=hell world

ret wstring=hell world
ret wstring=hell world
请按任意键继续. . .

分享到:
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: hlamps#outlook.com (#换成@)。
相关文章
{{ v.title }}
{{ v.description||(cleanHtml(v.content)).substr(0,100)+'···' }}
你可能感兴趣
推荐阅读 更多>