20

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

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
YAKOVM
  • 9,805
  • 31
  • 116
  • 217

4 Answers4

35

In C++ 11 you may just use:

std::to_string()

it's defined in header

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

dau_sama
  • 4,247
  • 2
  • 23
  • 30
12

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();
Flexo
  • 87,323
  • 22
  • 191
  • 272
5

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);
jcoder
  • 29,554
  • 19
  • 87
  • 130
2
string genString(uint64_t val)
{
   char temp[21];
   sprintf(temp, "%z", val);
   return temp;
}
NMI
  • 134
  • 1
  • 8
  • To whomever may use this in the future, make sure to make your buffer big enough. Also you could make that buffer `static` if you wanted to add a little more efficiency. – Seth Carnegie Sep 08 '11 at 12:44
  • 1
    @Seth - is static (and hence not reentrant) really faster than changing the stack pointer increase at entering the function from `n` to `n + 21`? – Flexo Sep 08 '11 at 12:56
  • @Seth - gcc 4.4 with -O3 on ia32 gives me the exact opposite behaviour. `static` makes it consistently (slightly) slower (more than the error) on 100 repetitions of a 10,000,000 call loop. Seems like premature optimisation to me. The main chance in the local version is `subl $72, %esp` vs `subl $52, %esp`, an O(1) change. – Flexo Sep 08 '11 at 13:42
  • @nmi - I don't think `%z` is correct - I get `test.cc:10:29: warning: conversion lacks type at end of format` and `test.cc:10:29: warning: too many arguments for format` with gcc – Flexo Sep 08 '11 at 13:43