System::String *,char*,string 等的类型转换

在VC 的编程中,经常会用到各种类型的转换,在MFC中textbox等控件得到的返回类型是System::String *,而写入的文件要求是 const char *类型的,下面介绍一些转换的方法:
string 转 CString    CString.format("%s", string.c_str());

char* 转 CString    CString.format("%s", char*);

char* 转 string       string change=new string s(char *);

string 转 char *     char *p = string.c_str();

CString转std::string CString str = dlg.GetPathName();
                           setlocale(LC_ALL, "chs");
                          char *p = new char[256];
                        wcstombs( p, str, 256 );
                         m_fileName = p;

int 转CString而将数字转换为CString变量,

                    可以使用CString的Format函数
                      CString s;  
                      int i = 64;  
                     s.Format("%d", i)  
     Format函数的功能很强,值得你研究一下。

CString TO char *    

    要把CString转成char *,用操作符(LPCSTR

                               
CString转换 char[100]  

         char a[100];  
      CString str("aaaaaa");  
     strncpy(a,(LPCTSTR)str,sizeof(a));
CString类型的转换成int    

            CString aaa = "16" ;
       int int_chage = atoi((lpcstr)aaa) ;

char* 在装int     

          #include <stdlib.h>
          int atoi(const char *nptr);
           long atol(const char *nptr);
          long long atoll(const char *nptr);
          long long atoq(const char *nptr);

System::String 转化成 char *类型(网上提供有许多种类)

1 MSDN上的

#include < stdio.h >
#include < stdlib.h >
#include < vcclr.h >   
using namespace System;   
int main() {
String ^str = "Hello";   
        pin_ptr<const wchar_t> wch = PtrToStringChars(str);
printf_s("%S\n", wch);   
        size_t convertedChars = 0;
size_t sizeInBytes = ((str->Length 1) * 2);
errno_t err = 0;
char     *ch = (char *)malloc(sizeInBytes);   
   err= wcstombs_s(&convertedChars, ch, sizeInBytes, wch,sizeInBytes);
if (err != 0)    printf_s("wcstombs_s failed!\n");   
          printf_s("%s\n", ch);
}

2 网上找的

PtrToStringChars 指定了一个指向实际 String 对象的内部指针。如果将此指针传递给非托管函数调用,则必须先锁定该指针,以确保在进行异步垃圾回收过程中对象不会移动:

//#include <vcclr.h>
System::String * str = S"Hello world\n";
const __wchar_t __pin * str1 = PtrToStringChars(str);
wprintf(str1);
3 感觉这种最好用的

StringToHGlobalAnsi 将托管 String 对象的内容复制到本机堆,

然后动态地将它转换为美国国家标准学会 (ANSI) 格式。

此方法将分配所需的本机堆内存:

using namespace System;

using namespace System::Runtime::InteropServices;
System::String * str = S"Hello world\n";
char* str2 = (char*)(void*)Marshal::StringToHGlobalAnsi(str);
printf(str2);

    希望对大家的编程有所帮助

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值