Convert uint64_t to std::string

38,058

Solution 1

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();

Solution 2

In C++ 11 you may just use:

std::to_string()

it's defined in header

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

Solution 3

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);

Solution 4

string genString(uint64_t val)
{
   char temp[21];
   sprintf(temp, "%z", val);
   return temp;
}
Share:
38,058
YAKOVM
Author by

YAKOVM

Updated on July 09, 2022

Comments

  • YAKOVM
    YAKOVM almost 2 years

    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

  • YAKOVM
    YAKOVM over 12 years
    Can you give me the code example how to use std::ostringstream?
  • Flexo
    Flexo over 12 years
    @yakov - added examples for both. You'll need either #include <boost/lexical_cast.hpp> or #include <sstream> depending on which solution you use.
  • Seth Carnegie
    Seth Carnegie over 12 years
    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.
  • Flexo
    Flexo over 12 years
    @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
    Flexo over 12 years
    @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
    Flexo over 12 years
    @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
  • Liosan
    Liosan over 7 years
    Downvoted since by now, the standard C++11 solution should be used - std::to_string.