65.9K
CodeProject 正在变化。 阅读更多。
Home

CString 到 char 转换方法(无警告)

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (8投票s)

2005年10月12日

viewsIcon

87713

一篇关于将 CStrings 转换为 chars 而不丢失数据的文章。

引言

当我开始在 Visual Studio 中编写代码时,我很难找到关于如何将 CString 转换为 char 的清晰信息。 我的许多应用程序都会根据用户提供的信息创建多个配置文件。 我更喜欢使用旧的 C 风格的文件处理方式,而不是 MFC 的 CFile,但要做到这一点,你必须将任何 CString 转换为 char 用于文件名。 最初,我编写了一个函数来执行此任务,否则 Visual Studio 会给出臭名昭著的“转换为 char 可能会丢失数据”警告。 我更喜欢我的代码没有警告。 我知道这只是一个小怪癖。 无论如何,这里是一个操作指南。 承认这可能看起来微不足道,但我在努力获得答案时感到非常沮丧。

使用代码

使用代码很简单。 可以将以下代码剪切并粘贴到你的应用程序中,并更改任何变量以适应,或者根据需要应用该方法。

//
// Convert CString to Char By Quintin Immelman.
//
CString DummyString;
// Size Can be anything, just adjust the 100 to suit. 
const size_t StringSize = 100;
// The number of characters in the string can be
// less than String Size. Null terminating character added at end.
size_t CharactersConverted = 0;
 
char DummyToChar[StringSize];
 
wcstombs_s(&CharactersConverted, DummyToChar, 
           DummyString.GetLength()+1, DummyString, 
           _TRUNCATE);
//Always Enter the length as 1 greater else 
//the last character is Truncated

关注点

就是这样。 终于有了干净、无“警告”的代码。

历史

  • 最后更新:2005年10月7日
© . All rights reserved.