I thought this would be really simple but it\'s presenting some difficulties. If I have
std::string name = \"John\";
int age = 21;
How do I
It seems to me that the simplest answer is to use the sprintf
function:
sprintf(outString,"%s%d",name,age);
#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}
If you are using MFC, you can use a CString
CString nameAge = "";
nameAge.Format("%s%d", "John", 21);
Managed C++ also has a string formatter.
This is the easiest way:
string s = name + std::to_string(age);
Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.
#include <iostream>
#include <locale>
#include <string>
template <class Facet>
struct erasable_facet : Facet
{
erasable_facet() : Facet(1) { }
~erasable_facet() { }
};
void append_int(std::string& s, int n)
{
erasable_facet<std::num_put<char,
std::back_insert_iterator<std::string>>> facet;
std::ios str(nullptr);
facet.put(std::back_inserter(s), str,
str.fill(), static_cast<unsigned long>(n));
}
int main()
{
std::string str = "ID: ";
int id = 123;
append_int(str, id);
std::cout << str; // ID: 123
}
In C++20 you'll be able to do:
auto result = std::format("{}{}", name, age);
In the meantime you can use the {fmt} library, std::format
is based on:
auto result = fmt::format("{}{}", name, age);
Disclaimer: I'm the author of the {fmt} library and C++20 std::format
.