2
votes

I am having a weird problem with CString I have the following code which gives an unexpected result:

CString sourcePath = _T("C:\\some\\path\\file.ext");
CString log;
log.Format(_T("Path = %s"), sourcePath);

the result string shows Path = (null).

I am not sure what is going on under the hood there, I have tried casting the sourcePath to an LPCTSTR and got a valid pointer and when viewing the content of that memory address in the memory view window of MSVC everything seems valid.

this annoys me as I have tried the same method in previous projects and it worked pretty well.

Thanks.

P.S. Please, before people start commenting here asking about what is a CString, as it happened in an earlier post of mine, please check here first: MSDN CString

Edit: sorry about the slash thingy.. and yes the original code does have double slashes..

4
This sample doesn't reproduce the problem here. Have you checked for buffer overflows that could affect sourcePath? Is this your literal code, or does other things happen in between the 3 lines you've shown? - Erik
@Erik, I just tested this with Visual Studio 2010 and Visual Studio 2008 and was unable to duplicate the problem as well. There must be some other code going on in between. - Justin
Got the same problem. Oh, yes, I have some old projects with MFC ;) VS2012 and VS6 can reproduce this problem. My format string was "some text %s, some text: %d, %d, %s text %s". First string was ok, but the second and third are not - only "(null)". So I divided this massive format string into two smaller and now it looks good. Third string was added without format. One %s per format string. - crea7or

4 Answers

0
votes

As your MSDN CString link also mentions, you cannot pass the CString itself to the Format function.

Use:

  log.Format(_T("Path = %s"), sourcePath.GetString());
0
votes

The string "C:\some\path\file.ext" should be "C:\some\path\file.ext" - otherwise you will read control characters (\s \p \f) instead.

0
votes

Depending on the MFC version and whether your app is built for win32 or x64, you might have to cast the CString:

log.Format(_T("Path = %s"), (LPCTSTR)sourcePath);
0
votes

There is a problem in your sourcePath initialization. The character \ is a special character in C/C++. You should replace it with \ (double ) So the first line of code should be: CString sourcePath = _T("C:\\some\\path\\file.ext");

Hope this helps.