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\n", (LPCWSTR)cstring); // Okay. Becase it has an operator LPCWSTR()
wprintf(L"%s\n", cstring); // Okay, fine. But how?
wprintf(L"%s\n", (LPCWSTR)s); // Okay. fine.
wprintf(L"%s\n", 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\n", howmany, (LPCTSTR)kindOfFruit );
A CString object keeps character data in a CStringData object. CString accepts NULL-terminated C-style strings. CString tracks the string length for faster performance, but it also retains the NULL character in the stored character data to support conversion to LPCWSTR .
You can assign C-style literal strings to a CString just as you can assign one CString object to another. Assign the value of a C literal string to a CString object. CString myString = _T("This is a test"); Assign the value of one CString to another CString object.
string. h places the identifiers in the global namespace, and may also place them in the standard namespace. While cstring places the identifiers in the standard namespace, and may also place them in the global namespace.
CString is specifically designed such that it only contains a pointer that points to the string data in a buffer class. When passed by value to printf it will be treated as a pointer when seeing the "%s" in the format string.
It originally just happened to work with printf by chance, but this has later been kept as part of the class interface.
This post is based on MS documentation long since retired, so I cannot link to their promise that they will continue to make this work.
However, before adding more downvotes please also read this blog post from someone sharing my old knowledge:
Big Brother helps you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With