Concatenating a std::string and an int
Combining a std::string and an int to form a single string can be a straightforward task. Here are multiple approaches to achieve this:
1. Using Boost
#include <boost/lexical_cast.hpp> std::string name = "John"; int age = 21; std::string result = name + boost::lexical_cast<std::string>(age);
2. Using C 11
std::string name = "John"; int age = 21; std::string result = name + std::to_string(age);
3. Using FastFormat
#include <fastformat/format.hpp> std::string name = "John"; int age = 21; std::string result; fastformat::fmt(result, "{0}{1}", name, age); // FastFormat.Format fastformat::write(result, name, age); // FastFormat.Write
4. Using the {fmt} library
#include <fmt/core.h> std::string name = "John"; int age = 21; std::string result = fmt::format("{}{}", name, age);
5. Using IOStreams
std::string name = "John"; int age = 21; std::stringstream sstm; sstm << name << age; std::string result = sstm.str();
6. Using itoa
std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits std::string result = name + itoa(age, numstr, 10);
7. Using sprintf
std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits sprintf(numstr, "%d", age); std::string result = name + numstr;
8. Using STLSoft's integer_to_string
#include <stlsoft/integer_to_string.hpp> std::string name = "John"; int age = 21; char numstr[21]; // enough to hold all numbers up to 64-bits std::string result = name + stlsoft::integer_to_string(numstr, 21, age);
9. Using STLSoft's winstl::int_to_string()
#include <stlsoft/winstl/int_to_string.hpp> std::string name = "John"; int age = 21; std::string result = name + winstl::int_to_string(age);
10. Using Poco NumberFormatter
#include <Poco/NumberFormatter.h> std::string name = "John"; int age = 21; std::string result = name + Poco::NumberFormatter().format(age);
The above is the detailed content of How Can I Concatenate a std::string and an Integer in C ?. For more information, please follow other related articles on the PHP Chinese website!