class MyString
{
public:
MyString(const std::wstring& s2)
{
s = s2;
}
operator LPCWSTR() const
{
return s.c_str();
}
private:
std::wstring s;
};
int _tmain(int argc, _TCHAR* argv[])
{
MyString s = L"MyString";
CStringW cstring = L"CString";
wprintf(L"%s
", (LPCWSTR)cstring); // Okay. Becase it has an operator LPCWSTR()
wprintf(L"%s
", cstring); // Okay, fine. But how?
wprintf(L"%s
", (LPCWSTR)s); // Okay. fine.
wprintf(L"%s
", s); // Doesn't work. Why? It prints gabage string like "?."
return 0;
}
How can CString be passed to format string %s?
By the way, MSDN says(it's weird)
To use a CString object in a variable argument function
Explicitly cast the CString to an LPCTSTR string, as shown here:
CString kindOfFruit = "bananas";
int howmany = 25;
printf( "You have %d %s
", howmany, (LPCTSTR)kindOfFruit );
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…