Ben*_*min 13 c++ windows string type-conversion string-formatting
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;
}
Run Code Online (Sandbox Code Playgroud)
如何将CString传递给格式字符串%s?
在变量参数函数中使用CString对象
将CString显式地转换为LPCTSTR字符串,如下所示:
CString kindOfFruit = "bananas";
int howmany = 25;
printf( "You have %d %s\n", howmany, (LPCTSTR)kindOfFruit );
Run Code Online (Sandbox Code Playgroud)
wprintf(L"%s\n", (LPCWSTR)cstring); // Okay. It's been cast to a const wchar_t*.
wprintf(L"%s\n", cstring); // UNDEFINED BEHAVIOUR
wprintf(L"%s\n", (LPCWSTR)s); // Okay, it's a const wchar_t*.
wprintf(L"%s\n", s); // UNDEFINED BEHAVIOUR
Run Code Online (Sandbox Code Playgroud)
在只有你可以通过这个功能的事情%s是const wchar_t*.其他任何东西都是未定义的行为.传递CString恰好可以正常工作.
有一个原因iostream是用C++开发的,这是因为这些变量参数函数非常不安全,并且永远不会被使用.哦,CString也是一个很大的罪恶,有很多理由,坚持std::wstring和cout/ wcout无论你在哪里.
| 归档时间: |
|
| 查看次数: |
29726 次 |
| 最近记录: |