如何摆脱从格式消息A附加到错误消息的".rn"字符?
How to get rid of the ". " characters appended to the error message from FormatMessageA?
我正在用std::errc替换boost::system::error_code。error_code支持通过error_code::message()以字符串格式显示错误消息。但我认为在STL中,我们没有一个预定义的方法来做它。我说的对吗?
如果我错了,请告诉我默认的方法,而不需要我自己写函数。如果我是对的,请帮我格式化下面程序中的错误信息(取自stackoverflow)
//Returns the last Win32 error, in string format. Returns an empty string if there is no error.
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
int main()
{
SetLastError((DWORD)std::errc::operation_canceled);
string str(GetLastErrorAsString());
cout << "str = " << str;
return 0;
}
输出:str =该信号量之前的所有权已经结束。rn
boost::system::error_code::message()的输出没有这些额外的".rn"。是否有办法通过调整提供给FormatMessageA()的参数,我们可以去掉这些额外的字母?或者我必须割自己(简单地去掉后面的3个字符)?如果我只是盲目地剪掉它们,有没有可能,错误信息中没有这些字符?
添加下列标志有效;
FORMAT_MESSAGE_MAX_WIDTH_MASK (0x000000FF):该函数忽略regular消息定义文本中的换行符。函数存储将消息定义文本中的硬编码换行符放入输出中缓冲区。该函数不生成新的换行符。
std::string GetLastErrorAsString()
{
//Get the error message, if any.
DWORD errorMessageID = ::GetLastError();
LPSTR messageBuffer = nullptr;
size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);
std::string message(messageBuffer, size);
//Free the buffer.
LocalFree(messageBuffer);
return message;
}
int main()
{
SetLastError((DWORD)std::errc::operation_canceled);
string str(GetLastErrorAsString());
cout << "str = " << str;
return 0;
}
我已经为你做了所有辛苦的工作:
while (size && isspace (messageBuffer[size-1]))
messageBuffer[--size] = 0;
if (size && messageBuffer[size-1] == '.')
messageBuffer[--size] = 0;
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- boost::进程间消息队列引发错误
- 为什么 Serial.println(<char[]>);返回随机字符?
- 如果用户输入的字符过多,则创建错误消息
- 字符* 文本消息[] 如何在内存中格式化?
- 如何将没有终止字符和大小的返回消息一起使用提升async_read?
- 从DLL文件调用消息框函数时出现奇怪的字符
- Arduino不支持使用websocket协议发送超过65535个字符的消息
- 套接字Java到C++-消息的长度总是8192个字符
- InternetGetLastResponseInfo返回奇怪的字符,而不是错误消息
- 网络消息格式化很多字符,int,在CC++中转换
- 使用发送消息设置文本框文本 设置文本仅发送字符串 win32 c++ 的第一个字符
- 了解从TranslateMessage()发送的字符消息顺序
- 在消息中显示每个字符的十六进制
- Zeromq:如何从python客户端向c++服务器发送超过30个字符的消息
- 消息框第一个字符或单词错误
- 从WM_KEYDOWN消息检测非字符按
- 当我使用 win32 发送消息发送和转换标准字符串时,我得到奇怪的字符
- 如何摆脱从格式消息A附加到错误消息的".rn"字符?