字符指针与字符串变量的转换

VC.NET中的String类是利用Unicode字符集编码来表示文本。Unicode字符集中每个字符(汉字、英文字母)都占2个字节,且其字符串是以2个连续的/0结尾的。

ANSI的ASCII字符集是最常见的字符集,常用于表示txt的文本文件。在ASCII字符集中英文占一个字节,汉字2个字节,且其字符串是以一个/0结尾的。
在利用VC.NET进行混合编程时,经常需要实现String与char*的互转,例如在TextBox控件中输入的Text作为fopen或者CreateFile的文件名参数时,常需要实现char*的转化。故提供如下的转化方法:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>

int main(array<System::String ^> ^args)
{
 // String^ converts to char*

 char szDestOutChar[256];

 String^ SrcInStr = "C://Documents and Settings//Adiminstrator//我的文档//swq.txt ";

 int SourceStrLen = SrcInStr->Length;
 wchar_t *pwszStr = new wchar_t[SourceStrLen + 1];
 array <System::Char>^ pClr = SrcInStr->ToCharArray();

 for (int i = 0; i < SourceStrLen; i++)
 {
   pwszStr[i] = pClr[i];
 }
ourceStrLen] = '/0';
 ::WideCharToMultiByte(CP_ACP, NULL, pwszStr, -1, szDestOutChar, 256, NULL, NULL);

 // char* converts to String^

 char* szInSrcChar =  "C://Documents and Settings//Adiminstrator//我的文档//swq.txt";
 int wcsLen = ::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), NULL, 0);
 wchar_t* wszStr = new wchar_t[wcsLen + 1];
 ::MultiByteToWideChar(CP_ACP, NULL, szInSrcChar, strlen(szInSrcChar), wszStr, wcsLen);
 wszStr[wcsLen] = '/0';

 String^ ClrOutStr = gcnew String(wszStr);

 System::Console::WriteLine("Press ENTER key to exit !");
 System::Console::Read();

 delete pwszStr
delete wszStr;
 return 0;
}

详细出处参考:http://www.itqun.net/content-detail/75523_3.html

详细出处参考:http://www.itqun.net/content-detail/75523_2.html

详细出处参考:l

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值