Concatenating a std::string and an int
Combining a std::string and an int to form a single string can be a seemingly straightforward task, yet it may present some challenges. Let's tackle the given example:
std::string name = "John"; int age = 21;
To concatenate these elements into "John21," several approaches are available.
With Boost
Using Boost's lexical_cast, you can convert the int to a string and append it:
#include <boost/lexical_cast.hpp> std::string result = name + boost::lexical_cast<std::string>(age);
With C 11
In C 11, the std::to_string function provides a convenient way to convert an int to a string:
std::string result = name + std::to_string(age);
With FastFormat
FastFormat offers both Format and Write methods for string concatenation:
#include <fastformat/format.hpp> fastformat::fmt(result, "{0}{1}", name, age); fastformat::write(result, name, age);
With the {fmt} library
The {fmt} library provides a concise syntax for string formatting:
#include <fmt/core.h> std::string result = fmt::format("{}{}", name, age);
With IOStreams
Using an IO stream is a more verbose but standard C approach:
#include <sstream> std::stringstream sstm; sstm << name << age; std::string result = sstm.str();
With itoa
Itoa (Integer-to-String) is a non-standard extension that converts an int to a string:
#include <stdlib.h> char numstr[21]; // Ensure sufficient buffer size std::string result = name + itoa(age, numstr, 10);
With sprintf
Sprintf is another non-standard extension that formats an int into a string:
#include <cstdio> char numstr[21]; // Ensure sufficient buffer size sprintf(numstr, "%d", age); std::string result = name + numstr;
With STLSoft's integer_to_string
STLSoft provides a specialized function for converting an int to a string:
#include <stlsoft/string_algo.h> char numstr[21]; // Ensure sufficient buffer size std::string result = name + stlsoft::integer_to_string(numstr, 21, age);
With STLSoft's winstl::int_to_string
This function, specific to Windows, provides an efficient and safe conversion:
#include <stlsoft/winstl/int_to_string.hpp> std::string result = name + winstl::int_to_string(age);
With Poco NumberFormatter
Poco's NumberFormatter can be used for formatting numbers as strings:
#include <Poco/NumberFormatter.h> std::string result = name + Poco::NumberFormatter().format(age);
In summary, the chosen approach may vary depending on your specific requirements and platform. Consider performance, safety, and portability when selecting the most suitable solution for concatenating a std::string and an int.
The above is the detailed content of How to Efficiently Concatenate a std::string and an int in C ?. For more information, please follow other related articles on the PHP Chinese website!