---
title: "VC char和TCHAR之间转换"
author: "jishublog"
date: "2013-09-22T17:40:00Z"
tags: []
slug: "vc-char-tchar"
draft: false
lastmod: "2013-09-22T19:29:11Z"
id: 1945398
url: "https://jishublog.iteye.com/blog/1945398"
---

[**char**](http://baike.baidu.com/view/1006519.htm)：计算机编程语言（c、c++、java、VFP等）中可容纳单个字符的一种基本数据类型。

[**TCHAR**](http://baike.baidu.com/view/2901835.htm)：为了满足Unicode编码，对char的扩展，即\_T(“str”)表示TCHAR类型

C++支持两种字符串，即常规的ANSI编码（使用""包裹）和Unicode编码（使用L""包裹），这样对应的就有了两套字符串字符串处理函数，比如：strlen和wcslen，分别用于处理两种字符串char和TCHAR类型

winnt.h头文件中：

typedef WCHAR TCHAR, \*PTCHAR;

表明 TCHAR 与 WCHAR 属同一类型

char szA\[100]; //ANSIstring buffer

WCHAR szW\[100]; //Unicodestring buffer

// Normal sprintf:all strings are ANSI  
**sprintf(szA, "****%s****","ANSI Str");**

// Converts Unicode string to ANSI  
sprintf(szA,"%S",L"Unicode Str");

// Normal swprintf:all strings are Unicode  
swprintf(szW,L"**%s**",L"Unicode Str");

// Converts ANSI string to Unicode

swprintf(szW,L"**%S**", "ANSI Str");

**注意：**大写S 和小写s 的使用

===========================

**应用实例：**通过system函数程序调用启动msc程序

**\[cpp]**[view plain](http://blog.csdn.net/ithomer/article/details/7794003 "view plain")[copy](http://blog.csdn.net/ithomer/article/details/7794003 "copy")[print](http://blog.csdn.net/ithomer/article/details/7794003 "print")[?](http://blog.csdn.net/ithomer/article/details/7794003 "?")

01. voidWSUS::OnBnClickedOk()
02. {
03. CStringstrPath=NULL;//申请路径字符串（TCHAR）
04. charstrChar\[256];//申请路径字符串（char）
05. m\_CustomEdit.GetWindowTextW(strPath);//获取路径存储到strPath
06. strPath.Replace(\_T("\\\\"),\_T("\\\\\\\\"));//替换strPath中"\\"为"\\\\"，注意转换符
07. //sprintf(strChar,"%s%S","mmc.exe",strPath);//TCHAR转换char类型
08. sprintf(strChar,"mmc.exe\\"%S\\"",strPath);//TCHAR转换char类型
09. MessageBox(strPath,\_T("title"));
10. system(strChar);//系统函数调用启动msc程序
11. //WinExec((LPCSTR)\_bstr\_t(strPath),SW\_SHOW);//调用exe程序
12. }

**示例步骤：**

1、获取msc程序路径strPath

![](http://my.csdn.net/uploads/201207/27/1343377860_4299.png)

2、替换strPath中"\\"为"\\\\"字符

C:\\Windows\\System32\\gpedit.msc

首先，通过strPath.Replace(\_T("\\\\"), \_T("\\\\\\\\"));转换成：

C:\\\\Windows\\\\System32\\\\gpedit.msc

然后，通过sprintf(strChar, "%s %S", "mmc.exe", strPath);拼接字符串为：

mmc.exeC:\\\\Windows\\\\System32\\\\gpedit.msc

3、system函数调用启动msc程序  
system(strChar);

4、启动结果如下

![](http://my.csdn.net/uploads/201207/27/1343378345_9663.png)