2006-07-31

Visual C 如何:在各种字符串类型之间进行转换

来源: CSDN 作者:guanchanghui 评论 0 条
 

本主题演示如何将各种 C 字符串类型转换为其他字符串。可以转换的字符串类型包括 char *wchar_t*、_bstr_t、CComBSTR、CString、basic_string 和 System.String。在所有情况下,在将字符串转换为新类型时,都会创建字符串的副本。对新字符串进行的任何更改都不会影响原始字符串,反之亦然。

从 char * 转换

示例

说明

此示例演示如何从 char * 转换为上面列出的其他字符串类型。

// convert_from_char.cpp

// compile with /clr /link comsuppw.lib



#include <iostream>

#include <stdlib.h>

#include <string>



#include "atlbase.h"

#include "atlstr.h"

#include "comutil.h"



using namespace std;

using namespace System;



int main()

{

    char *orig = "Hello, World!";

    cout << orig << " (char *)" << endl;



    // Convert to a wchar_t*

    size_t origsize = strlen(orig)   1;

    const size_t newsize = 100;

    size_t convertedChars = 0;

    wchar_t wcstring[newsize];

    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);

    wcscat_s(wcstring, L" (wchar_t *)");

    wcout << wcstring << endl;



    // Convert to a _bstr_t

    _bstr_t bstrt(orig);

    bstrt  = " (_bstr_t)";

    cout << bstrt << endl;



    // Convert to a CComBSTR

    CComBSTR ccombstr(orig);

    if (ccombstr.Append(L" (CComBSTR)") == S_OK)

    {

        CW2A printstr(ccombstr);

        cout << printstr << endl;

    }



    // Convert to a CString

    CString cstring(orig);

    cstring  = " (CString)";

    cout << cstring << endl;



    // Convert to a basic_string

    string basicstring(orig);

    basicstring  = " (basic_string)";

    cout << basicstring << endl;



    // Convert to a System::String

    String ^systemstring = gcnew String(orig);

    systemstring  = " (System::String)";

    Console::WriteLine("{0}", systemstring);

    delete systemstring;

}

输出

Hello, World! (char *)

Hello, World! (wchar_t *)

Hello, World! (_bstr_t)

Hello, World! (CComBSTR)

Hello, World! (CString)

Hello, World! (basic_string)

Hello, World! (System::String)

从 wchar_t * 转换

示例

说明
共5页: 上一页 1 [2] [3] [4] [5] 下一页

(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:教你用Myisamchk进行崩溃恢复MySQL  
下一篇:MySQL加密函数保护Web网站敏感数据
    评论加载中…
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号