【发布时间】:2019-07-20 21:22:24
【问题描述】:
我遇到了一个非常奇怪的问题。
我希望在 Windows 上使用 MessageBox(扩展为 MessageBoxW)输出一个简单的字符串。
以下是我正在使用的方法:
void MainWindow::ShowMessageBox( const std::wstring& title,const std::wstring& message ) const
{
MessageBox( hWnd,message.c_str(),title.c_str(),MB_OK );
}
std::wstring ConversionHelpers::s2ws(const std::string& s)
{
int len;
int slength = (int)s.length() + 1;
len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
std::wstring r(buf);
delete[] buf;
return r;
}
void DebugHelpers::MsgBox(MainWindow& window, const char* title, const char* message)
{
std::string t(title);
std::string m(message);
window.ShowMessageBox(ConversionHelpers::s2ws(t), ConversionHelpers::s2ws(m));
}
这行得通:
MsgBox(wnd, "Test", std::string("Hello").c_str());
这不起作用:
const char* get_hello()
{
return std::string("Hello").c_str();
}
MsgBox(wnd, "Test", get_hello());
“不起作用”是指我得到了大量奇怪的字符。
我知道在此示例中不需要转换,但在我的实现中,这是必要的。但这并不能回答关于奇怪的问题。
我对两者都做同样的事情,但是使用一种方法来返回值,而不是直接访问它。
【问题讨论】:
-
字符串字面量转换为wstring,尝试在它前面放一个L,L"test"
-
std::wstring中的w代表wchar_t和宽字符。它们不同于使用char的窄字符。 -
@chris:你是对的。
-
犯了一个小错误,更新问题
-
@RickyFisher 调试那些转换函数。这是完成大部分工作的地方。
标签: c++