Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can CString be passed to format string %s?

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 ); 
like image 677
Benjamin Avatar asked Jul 07 '11 10:07

Benjamin


People also ask

What is the use of CString in C++?

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 .

How do you assign CString?

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.

What is the difference between CString and string h?

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.


1 Answers

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

like image 88
Bo Persson Avatar answered Oct 04 '22 20:10

Bo Persson