views:

139

answers:

2

The following code is generating warning C6284 when compiled with /analyze on MSVC 2008 : object passed as parameter '%s' when string is required in call to function.

 CString strTmp, str;
 str = L"aaa.txt"
 strTmp.Format (L"File: %s", str);

I'm looking for a nice solution for this that would not require static_cast

+2  A: 

Microsoft describes the usage of CString with variable argument functions here:

CString  kindOfFruit = "bananas";
int      howmany = 25;
printf_s( "You have %d %s\n", howmany, (LPCTSTR)kindOfFruit ); 

As an alternative you can also use the method PCXSTR CString::GetString() const; to try to fix the warning:

CString strTmp, str;
str = L"aaa.txt"
strTmp.Format (L"File: %s", str.GetString());
Frank Bollack
Am I wrong or the correct solution is to use `str.GetBuffer()` ?
Sorin Sbarnea
You could use both for your situation, but they have different meanings to the reader. `GetBuffer()` returns a string buffer that allows for direct modification (not `const`) of the `CString` object whereas `GetString()` returns a `const` buffer for read only access.
Frank Bollack
A: 

One of CString's design flaws, err, features is that it features an implicit conversion to LPCTSTR which makes the warning not that meaningful IMHO. But anyway, if you look at the Microsoft documentation, they actually use casts in their own example. I don't really see the need to avoid a static_cast here, in fact I would welcome it as it does make the implicit conversion more explicit and thus easier to spot.

Timo Geusch