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

99封情书 提交于 2019-11-27 07:35:38

问题


I have following code:

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

GetLastError() returns a DWORD a numeric value, but the constructor of std::string doesn't accept a DWORD.

What can I do?


回答1:


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();
} 



回答2:


You want to convert the number to a string:

std::ostringstream os;
os << GetLastError();
Log(os.str(), Error);

Or boost::lexical_cast:

Log(boost::lexical_cast<std::string>(GetLastError()), Error);



回答3:


Since C++11

std::to_string() with overloads for int, long, long long, unsigned int, unsigned long, unsigned long long, float, double, and long double.

auto i = 1337;
auto si = std::to_string(i); // "1337"
auto f = .1234f;
auto sf = std::to_string(f); // "0.123400"

Yes, I'm a fan of auto.

To use your example:

Tools::Logger.Log(std::to_string(GetLastError()), Error);



回答4:


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

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



回答5:


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.




回答6:


Use std::stringstream.

std::stringstream errorStream;
errorStream << GetLastError();
Tools::Logger.Log(errorStream.str(), Error);



回答7:


what i normally do is:

std::ostringstream oss;
oss << GetLastError() << " :: " << Error << std::endl;
Tools::Logger.Log(oss.str()); // or whatever interface is for logging



回答8:


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.



来源:https://stackoverflow.com/questions/893670/how-do-i-construct-a-stdstring-from-a-dword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!