Reputation:
My program is crashing in the wstringstream
line, I think it's because sometimes it searches for a msg
that doesn't exist inside of wmTranslation
, how I could 'fix' this?
const char* TranslateMessage(int Msg) {
static std::map<int, const char*> wmTranslation = {
{0, "WM_NULL" },
{1, "WM_CREATE" },
{2, "WM_DESTROY" },
//...
};
const char* translatedMessage = "Unknown message";
translatedMessage = wmTranslation[Msg];
return translatedMessage;
}
const char* translatedMessage = TranslateMessage(Msg);
std::wstringstream text;
text << L"Msg: " << Msg << L" - " << translatedMessage;
OutputDebugString(text.str().c_str());
Upvotes: 1
Views: 69
Reputation: 66371
Looking up a key that doesn't exist adds an entry for the key, with a default value (the null pointer in your case).
Check if the key exists first, then return the relevant value.
const char* TranslateMessage(int Msg) {
static std::map<int, const char*> wmTranslation = {
{0, "WM_NULL" },
{1, "WM_CREATE" },
{2, "WM_DESTROY" },
//...
};
auto it = wmTranslation.find(Msg);
return it != wmTranslation.end() ? it->second : "Unknown message";
}
If all the values are consecutive integers from zero upwards, you might consider using a vector (or an array) rather than a map, and index with Msg
.
Upvotes: 3