I am looking to convert a boost::uuid to a const char*. What is the correct syntax for the conversion?
Asked
Active
Viewed 3.7k times
5 Answers
63
Just in case, there is also boost::uuids::to_string
, that works as follows:
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_io.hpp>
boost::uuids::uuid a = ...;
const std::string tmp = boost::uuids::to_string(a);
const char* value = tmp.c_str();

SkorKNURE
- 731
- 5
- 2
-
2For people working with ancient boost versions: This method is introduced in 1.44. See http://www.boost.org/doc/libs/1_43_0/boost/uuid/uuid_io.hpp http://www.boost.org/doc/libs/1_44_0/boost/uuid/uuid_io.hpp – user1556435 Feb 17 '16 at 14:44
49
You can do this a bit easier using boost::lexical_cast that uses a std::stringstream under the hood.
#include <boost/lexical_cast.hpp>
#include <boost/uuid/uuid_io.hpp>
const std::string tmp = boost::lexical_cast<std::string>(theUuid);
const char * value = tmp.c_str();

larsmoa
- 12,604
- 8
- 62
- 85

user192610
- 606
- 5
- 2
-
after reading the boost documentation it seems to me that this answer is correct, however as per the documentation also indicates that to_string and to_wstring functions provided by boost::uuids is likely faster than boost::lexical_cast. [link](https://www.boost.org/doc/libs/1_64_0/libs/uuid/uuid.html) – Gr-Disarray Jul 17 '19 at 22:29
11
You can include <boost/uuid/uuid_io.hpp>
and then use the operators to convert a uuid into a std::stringstream
. From there, it's a standard conversion to a const char*
as needed.
For details, see the Input and Output second of the Uuid documentation.
std::stringstream ss;
ss << theUuid;
const std::string tmp = ss.str();
const char * value = tmp.c_str();
(For details on why you need the "tmp" string, see here.)

Community
- 1
- 1

Reed Copsey
- 554,122
- 78
- 1,158
- 1,373
1
You use the stream functions in boost/uuid/uuid_io.hpp.
boost::uuids::uuid u;
std::stringstream ss;
ss << u;
ss >> u;

Joe
- 41,484
- 20
- 104
- 125
1
boost::uuids::uuid u;
const char* UUID = boost::uuids::to_string(u).c_str();
It is possible to do a simple and quick conversion.

Matheus Toniolli
- 438
- 1
- 7
- 16