c++ - How to concatenate a std::string and an int? -
i thought simple it's presenting difficulties. if have
std::string name = "john"; int age = 21;
how combine them single string "john21"
?
in alphabetical order:
std::string name = "john"; int age = 21; std::string result; // 1. boost result = name + boost::lexical_cast<std::string>(age); // 2. c++11 result = name + std::to_string(age); // 3. fastformat.format fastformat::fmt(result, "{0}{1}", name, age); // 4. fastformat.write fastformat::write(result, name, age); // 5. iostreams std::stringstream sstm; sstm << name << age; result = sstm.str(); // 6. itoa char numstr[21]; // enough hold numbers 64-bits result = name + itoa(age, numstr, 10); // 7. sprintf char numstr[21]; // enough hold numbers 64-bits sprintf(numstr, "%d", age); result = name + numstr; // 8. stlsoft's integer_to_string char numstr[21]; // enough hold numbers 64-bits result = name + stlsoft::integer_to_string(numstr, 21, age); // 9. stlsoft's winstl::int_to_string() result = name + winstl::int_to_string(age); // 10. poco numberformatter result = name + poco::numberformatter().format(age);
- is safe, slow; requires boost (header-only); most/all platforms
- is safe, requires c++11 (to_string() included in
#include <string>
) - is safe, , fast; requires fastformat, must compiled; most/all platforms
- is safe, , fast; requires fastformat, must compiled; most/all platforms
- safe, slow, , verbose; requires
#include <sstream>
(from standard c++) - is brittle (you must supply large enough buffer), fast, , verbose; itoa() non-standard extension, , not guaranteed available platforms
- is brittle (you must supply large enough buffer), fast, , verbose; requires nothing (is standard c++); platforms
- is brittle (you must supply large enough buffer), probably fastest-possible conversion, verbose; requires stlsoft (header-only); most/all platforms
- safe-ish (you don't use more 1 int_to_string() call in single statement), fast; requires stlsoft (header-only); windows-only
- is safe, slow; requires poco c++ ; most/all platforms
Comments
Post a Comment