How do I construct a std::string from a DWORD?

前端 未结 8 2225
死守一世寂寞
死守一世寂寞 2020-12-07 00:30

I have following code:

Tools::Logger.Log(string(GetLastError()), Error);

GetLastError() returns a DWORD a numeric

相关标签:
8条回答
  • 2020-12-07 00:59

    Use Boost's lexical_cast for simple cases such as the above:

    Tools::Logger.Log(lexical_cast<string>(GetLastError()), Error);
    
    0 讨论(0)
  • 2020-12-07 01:00

    As all guys here suggested, implementation will use stringstream.
    In my current project we created function

    template <typename T>
    std::string util::str::build( const T& value );
    

    to create string from any source.

    So in our project it would be

    Tools::Logger.Log( util::str::build(GetLastError()) );
    

    Such usage of streams in the suggested way wouldn't pass my review unless someone wrap it.

    0 讨论(0)
  • 2020-12-07 01:12

    what i normally do is:

    std::ostringstream oss;
    oss << GetLastError() << " :: " << Error << std::endl;
    Tools::Logger.Log(oss.str()); // or whatever interface is for logging
    
    0 讨论(0)
  • 2020-12-07 01:14

    You can use STLSoft's winstl::int_to_string(), as follows:

    Tools::Logger.Log(winstl::int_to_string(GetLastError()), Error);
    

    Also, if you want to lookup the string form of the error code, you can use STLSoft's winstl::error_desc.

    There were a bunch of articles in Dr Dobb's about this a few years ago: parts one, two, three, four. Goes into the subject in great detail, particularly about performance.

    0 讨论(0)
  • 2020-12-07 01:19

    You want to read up on ostringstream:

    #include <sstream>
    #include <string>
    
    int main()
    {
       std::ostringstream stream;
       int i = 5;
       stream << i;
       std::string str = stream.str();
    } 
    
    0 讨论(0)
  • 2020-12-07 01:20

    Use std::stringstream.

    std::stringstream errorStream;
    errorStream << GetLastError();
    Tools::Logger.Log(errorStream.str(), Error);
    
    0 讨论(0)
提交回复
热议问题