Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert uint64_t to std::string

How can I transfer uint64_t value to std::string? I need to construct the std::string containing this value For example something like this:

void genString(uint64_t val)
{
      std::string str;
      //.....some code for str 
      str+=(unsigned int)val;//????
}

Thank you

like image 518
Yakov Avatar asked Sep 08 '11 12:09

Yakov


4 Answers

In C++ 11 you may just use:

std::to_string()

it's defined in header

http://www.cplusplus.com/reference/string/to_string/

like image 67
dau_sama Avatar answered Nov 13 '22 09:11

dau_sama


use either boost::lexical_cast or std::ostringstream

e.g.:

str += boost::lexical_cast<std::string>(val);

or

std::ostringstream o;
o << val;
str += o.str();
like image 40
Flexo Avatar answered Nov 13 '22 08:11

Flexo


I use something like this code below. Because it's a template it will work with any type the supports operator<< to a stream.

#include <sstream>

template <typename T>
std::string tostring(const T& t)
{
    std::ostringstream ss;
    ss << t;
    return ss.str();
}

for example

uint64_t data = 123;
std::string mystring = tostring(data);
like image 5
jcoder Avatar answered Nov 13 '22 07:11

jcoder


string genString(uint64_t val)
{
   char temp[21];
   sprintf(temp, "%z", val);
   return temp;
}
like image 2
NMI Avatar answered Nov 13 '22 08:11

NMI