Introduction
When I started coding in Visual Studio, I had a difficult time finding clear information on how to convert CString
s to char
s. 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.
CString DummyString;
const size_t StringSize = 100;
size_t CharactersConverted = 0;
char DummyToChar[StringSize];
wcstombs_s(&CharactersConverted, DummyToChar,
DummyString.GetLength()+1, DummyString,
_TRUNCATE);
Points of Interest
Easy as that. Good clean "warning" free code at last.
History
- Last updated: 07 October 2005