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); 
  1. is safe, slow; requires boost (header-only); most/all platforms
  2. is safe, requires c++11 (to_string() included in #include <string>)
  3. is safe, , fast; requires fastformat, must compiled; most/all platforms
  4. is safe, , fast; requires fastformat, must compiled; most/all platforms
  5. safe, slow, , verbose; requires #include <sstream> (from standard c++)
  6. is brittle (you must supply large enough buffer), fast, , verbose; itoa() non-standard extension, , not guaranteed available platforms
  7. is brittle (you must supply large enough buffer), fast, , verbose; requires nothing (is standard c++); platforms
  8. is brittle (you must supply large enough buffer), probably fastest-possible conversion, verbose; requires stlsoft (header-only); most/all platforms
  9. safe-ish (you don't use more 1 int_to_string() call in single statement), fast; requires stlsoft (header-only); windows-only
  10. is safe, slow; requires poco c++ ; most/all platforms

Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -