开发者

MFC CString Format gives weird behaviour

开发者 https://www.devze.com 2023-02-10 15:21 出处:网络
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\");

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 o开发者_如何转开发f 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..


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());


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


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);


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消