Domanda

Ho seguente codice:

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

GetLastError() restituisce un DWORD un valore numerico, ma il costruttore di std::string non accetta un DWORD.

Che cosa posso fare?

È stato utile?

Soluzione

Si vuole leggere su ostringstream:

#include <sstream>
#include <string>

int main()
{
   std::ostringstream stream;
   int i = 5;
   stream << i;
   std::string str = stream.str();
} 

Altri suggerimenti

Si desidera convertire il numero a un string:

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

O boost::lexical_cast:

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

Dal momento che C ++ 11

std::to_string() con sovraccarichi per int, long, long long, unsigned int, unsigned long, unsigned long long, float, double e long double.

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

Sì, io sono un fan di auto .

Per usare il tuo esempio:

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

L'utilizzo del lexical_cast per i casi semplici come Boost come sopra:

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

È possibile utilizzare STLSoft 's winstl :: INT_TO_STRING () , come segue:

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

Inoltre, se si vuole di ricercare la forma di stringa del codice di errore, è possibile utilizzare di STLSoft winstl :: error_desc .

Ci sono stati una serie di articoli in Dr Dobb di questo a pochi anni fa: le parti una , due , tre , quattro . Va l'argomento in grande dettagli, in particolare per le prestazioni.

L'uso std :: stringstream.

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

quello che faccio di solito è:

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

Come tutti i ragazzi qui suggerito, implementazione userà stringstream.
Nel mio progetto in corso che abbiamo creato la funzione

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

per creare stringa da qualsiasi fonte.

Quindi, nel nostro progetto che sarebbe stato

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

Tale utilizzo di flussi nel modo proposto non sarebbe passata la mia recensione a meno che qualcuno avvolgerla.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top