Correct/Best way to do convert int to string as uppercase hex ?
-
The following code will generate a random integer, then format this in uppercase hexidecimal, and then copy it to a std:string. Is there a better way of doing formatted output to a std:string ?
std::string sRandomString; std::ostringstream osRandomString; int x; x = (rand() << 16) | rand(); osRandomString << std::hex << std::uppercase << x; // formatted as uppercase unsigned hexadecimal integer sRandomString = osRandomString.str();
Why does it not work correctly when I usestd::ostringstream::hex
andstd::ostringstream::uppercase
? If I want to create multiple random strings by using a loop, am I right in thinking I just need to place the following line at the end of the loop, so that the next string generated will overwrite the previous string in the stream, instead of being appended to it ?osRandomString.seekp(0);
Is it necessary to place<< endl
or<< ends
after x where the formatting takes place ? eg.osRandomString << std::hex << std::uppercase << x << endl;
If yes, should I use endl or ends ? -
The following code will generate a random integer, then format this in uppercase hexidecimal, and then copy it to a std:string. Is there a better way of doing formatted output to a std:string ?
std::string sRandomString; std::ostringstream osRandomString; int x; x = (rand() << 16) | rand(); osRandomString << std::hex << std::uppercase << x; // formatted as uppercase unsigned hexadecimal integer sRandomString = osRandomString.str();
Why does it not work correctly when I usestd::ostringstream::hex
andstd::ostringstream::uppercase
? If I want to create multiple random strings by using a loop, am I right in thinking I just need to place the following line at the end of the loop, so that the next string generated will overwrite the previous string in the stream, instead of being appended to it ?osRandomString.seekp(0);
Is it necessary to place<< endl
or<< ends
after x where the formatting takes place ? eg.osRandomString << std::hex << std::uppercase << x << endl;
If yes, should I use endl or ends ?If you want to use STL strings, you might want to look at Boost.Format[^]. Then you could do something like:
osRandomString = boost::format("%X") % x;
It's basically a type-safe and more C++-ish version of printf. And there's so much other good stuff in Boost as well that you're doing yourself a favour by using it (IMO!).