Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / MFC

CString To char Conversion method (Warning Free)

3.00/5 (8 votes)
12 Oct 2005 1  
An article on converting CStrings to chars without data loss.

Introduction

When I started coding in Visual Studio, I had a difficult time finding clear information on how to convert CStrings to chars. Many of my applications create multiple files for configuration storage based on the information provided by the user. I prefer to use the old C style file handling as apposed to the MFC CFile but to do this you have to convert any CString to a char for the file name. At first I wrote a function to perform the task else Visual Studio gives the infamous "Conversion to char possible loss of data" warning. I prefer my code to be warning free. A small quirk I know. Any way here is a HowTo. Granted this may seem trivial but it frustrated the heck out of me trying to gain an answer.

Using the code

Using the code is simple. Either cut and paste the following code into your application and change any variables to suit or just apply the method as needed.

//
// 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

Points of Interest

Easy as that. Good clean "warning" free code at last.

History

  • Last updated: 07 October 2005

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here