views:

650

answers:

8

I have following code:

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

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

What can I do?

thanks in advance

+7  A: 

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

Tools::Logger.Log(lexical_cast<string>(GetLastError()), Error);
Konrad Rudolph
+15  A: 

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

Cheers

Johannes Schaub - litb
A: 

what i normally do is:

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

You want to read up on ostringstream:

int main()
{
   std::ostringstream stream;
   int i = 5;
   stream << i;
   std::string str = stream.str();
}
Doug T.
that's funny... who would downvote this? I wouldn't think this would be controversial :)
Doug T.
If you forget #include <sstream> you will get a strange error message: "error: aggregate ‘std::ostringstream ...’ has incomplete type and cannot be defined". Simple fix.
Jared Updike
A: 

Use std::stringstream.

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

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.

Mykola Golubyev
boost::lexical_cast already does this...
rlbond
Do you like how it looks? Can you specify it for work with doubles. For work with your own type which can't be used with the stream?
Mykola Golubyev
+3  A: 

I've linked this article before, by maybe one more time wouldn't hurt. Read The String Formatters of Manor Farm by Herb Sutter. It's a great comparison of the different ways to convert data to strings, including std::stringstream, Boost::lexical_cast, sprintf, snprintf, and std::strstream.

Fred Larson
+2  A: 

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.

dcw