Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent C6284 when using CString::Format?

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

like image 263
sorin Avatar asked Apr 08 '10 07:04

sorin


People also ask

What does CString mean in C++?

cstring is the header file required for string functions. This function Returns a pointer to the last occurrence of a character in a string.

How do you use CString in C++?

To use a CString object as a C-style string, cast the object to LPCTSTR . In the following example, the CString returns a pointer to a read-only C-style null-terminated string. The strcpy function puts a copy of the C-style string in the variable myString .


2 Answers

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());
like image 99
Frank Bollack Avatar answered Oct 17 '22 10:10

Frank Bollack


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.

like image 43
Timo Geusch Avatar answered Oct 17 '22 10:10

Timo Geusch