如何将CString传递到格式字符串%s? [英] How can CString be passed to format string %s?

查看:107
本文介绍了如何将CString传递到格式字符串%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;
}

CString如何传递到格式字符串%s?

How can CString be passed to format string %s?

顺便说一句, MSDN说< a>(很奇怪)

By the way, MSDN says(it's weird)


在变量参数函数中使用CString对象

将CString显式转换为一个LPCTSTR字符串,如下所示:

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 ); 


推荐答案

CString是专门设计的,指向缓冲区类中的字符串数据。它通过值传递给printf,然后在格式字符串中看到%s时将其视为一个指针。

CString is specifically designed such that it only contains a pointer that points to the string data in a buffer class. It is passed by value to printf which then treats it as a pointer when seeing the "%s" in the format string.

它最初只是使用printf机会,但这后来一直保持作为类接口的一部分。

It originally just happened to work with printf by chance, but this has later been kept as part of the class interface.

这篇关于如何将CString传递到格式字符串%s?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆