21 August 2014

####How to convert int to string std::string name = “John”; int age = 21; std::string result;

1 Boost

result = name + boost::lexical_cast<std::string>(age).

is safe, but slow; requires Boost (header-only); most/all platforms

2 FastFormat.Format

fastformat::fmt(result, "{0}{1}", name, age);

is safe, and fast; requires FastFormat, which must be compiled; most/all platforms

3 FastFormat.Write

fastformat::write(result, name, age);

is safe, and fast; requires FastFormat, which must be compiled; most/all platforms

4 IOStreams

std::stringstream sstm;
sstm << name << age;
result = sstm.str();


safe, slow, and verbose; requires nothing (is standard C++)

5 itoa

char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms

6 sprintf

char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms

7 STLSoft’s integer_to_string

char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

is brittle (you must supply a large enough buffer), probably the fastest-possible conversion, verbose; requires STLSoft (header-only); most/all platforms

8 STLSoft’s winstl::int_to_string()

result = name + winstl::int_to_string(age);

safe-ish (you don't use more than one int_to_string() call in a single statement), fast; requires STLSoft (header-only); Windows-only

9 Poco NumberFormatter

result = name + Poco::NumberFormatter().format(age);

is safe, but slow; requires Poco C++ ; most/all platforms