How to concatenate a std::string and an int?


How to concatenate a std::string and an int?



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 combine them to get a single string "John21"?


"John21"





Let me add to this: I tried 'str = "hi"; str += 5; cout << str;' and saw no effect. Turns out this calls operator+=(char) and adds a non-printable character.
– daveagp
Oct 25 '14 at 20:00





29 Answers
29



In alphabetical order:


std::string name = "John";
int age = 21;
std::string result;

// 1. with Boost
result = name + boost::lexical_cast<std::string>(age);

// 2. with C++11
result = name + std::to_string(age);

// 3. with FastFormat.Format
fastformat::fmt(result, "{0}{1}", name, age);

// 4. with FastFormat.Write (requires #include <sstream>)
fastformat::write(result, name, age);

// 5. with the {fmt} library
result = fmt::format("{}{}", name, age);

// 6. with IOStreams
std::stringstream sstm;
sstm << name << age;
result = sstm.str();

// 7. with itoa
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + itoa(age, numstr, 10);

// 8. with sprintf
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;

// 9. with STLSoft's integer_to_string
char numstr[21]; // enough to hold all numbers up to 64-bits
result = name + stlsoft::integer_to_string(numstr, 21, age);

// 10. with STLSoft's winstl::int_to_string()
result = name + winstl::int_to_string(age);

// 11. With Poco NumberFormatter
result = name + Poco::NumberFormatter().format(age);


#include <string>


#include <sstream>





Apart from the one link you've gfiven, what are you basing your performance comments on?
– JamieH
May 22 '09 at 21:45





See tinyurl.com/234rq9u for a comparison of some of the solutions
– Luca Martini
Oct 27 '10 at 14:08





Method #4 requires #include <sstream>, took me a while to figure out.
– Mandera
Sep 30 '14 at 11:39


#include <sstream>



In C++11, you can use std::to_string, e.g.:


std::to_string


auto result = name + std::to_string( age );



If you have Boost, you can convert the integer to a string using boost::lexical_cast<std::string>(age).


boost::lexical_cast<std::string>(age)



Another way is to use stringstreams:


std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;



A third approach would be to use sprintf or snprintf from the C library.


sprintf


snprintf


char buffer[128];
snprintf(buffer, sizeof(buffer), "%s%d", name.c_str(), age);
std::cout << buffer << std::endl;



Other posters suggested using itoa. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.


itoa





Note that snprintf is not guaranteed to null-terminate the string. Here's one way to make sure it works: <pre> char buffer[128]; buffer[sizeof(buffer)-1] = ''; snprintf(buffer, sizeof(buffer)-1, "%s%d", name.c_str(), age); std::cout << buffer << std::endl; </pre>
– Mr Fooz
Oct 10 '08 at 16:06





My tendency would be to never use sprintf, since this can result in buffer-overflows. The example above is a good example where using sprintf would be unsafe if the name was very long.
– terson
Oct 11 '08 at 18:06





note that snprintf is equally non-standard c++ (like itoa which you mention). it's taken from c99
– Johannes Schaub - litb
Feb 9 '09 at 3:36





an update on snprintf: it is included in C++11.
– David Foerster
Jul 3 '13 at 18:05


snprintf





@terson: I see no occurence of sprintf in the answer, only snprintf.
– David Foerster
Jul 3 '13 at 18:07


sprintf


snprintf


std::ostringstream o;
o << name << age;
std::cout << o.str();





this is great, BYT header file is sstream
– landerlyoung
Jan 13 '17 at 7:48


#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string itos(int i) // convert int to string
{
stringstream s;
s << i;
return s.str();
}



Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.





thanks for the code, link is broken now :D
– Bugs Happen
Nov 7 '16 at 17:12



This is the easiest way:


string s = name + std::to_string(age);





This is a post-C++11 solution!
– YamHon.CHAN
May 18 '15 at 3:30



It seems to me that the simplest answer is to use the sprintf function:


sprintf


sprintf(outString,"%s%d",name,age);





snprintf can be tricky (mainly because it can potentially not include the null character in certain situations), but I prefer that to avoid sprintf buffer overflows potential problems.
– terson
Oct 11 '08 at 18:08





sprintf(char*, const char*, ...) will fail on some versions of compilers when you pass a std::string to %s. Not all, though (it's undefined behavior) and it may depend on string length (SSO). Please use .c_str()
– MSalters
Oct 13 '08 at 10:42



If you have C++11, you can use std::to_string.


std::to_string



Example:


std::string name = "John";
int age = 21;

name += std::to_string(age);

std::cout << name;



Output:


John21





It would be name += std::to_string(static_cast<long long>(age)); in VC++ 2010 as you can see here
– neonmate
May 27 '14 at 15:40



name += std::to_string(static_cast<long long>(age));





@neonmate How about name += std::to_string(age + 0LL); instead?
– chux
Oct 7 '16 at 19:22


name += std::to_string(age + 0LL);


#include <string>
#include <sstream>
using namespace std;
string concatenate(std::string const& name, int i)
{
stringstream s;
s << name << i;
return s.str();
}



I don't have karma enough to comment (let alone edit), but Jay's post (currently the top-voted one at 27) contains an error. This code:


std::stringstream ss;
ss << age;
std::cout << name << ss.str() << std::endl;



Does not solve the stated problem of creating a string consisting of a concatenated string and integer. I think Jay meant something more like this:


std::stringstream ss;
ss << name;
ss << age;
std::cout << "built string: " << ss.str() << std::endl;



The final line is just to print the result, and shows how to access the final concatenated string.



Herb Sutter has a good article on this subject: "The String Formatters of Manor Farm". He covers Boost::lexical_cast, std::stringstream, std::strstream (which is deprecated), and sprintf vs. snprintf.


Boost::lexical_cast


std::stringstream


std::strstream


sprintf


snprintf


#include <sstream>

template <class T>
inline std::string to_string (const T& t)
{
std::stringstream ss;
ss << t;
return ss.str();
}



Then your usage would look something like this


std::string szName = "John";
int numAge = 23;
szName += to_string<int>(numAge);
cout << szName << endl;



Googled [and tested :p ]



If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:


+


operator+


template <typename L, typename R> std::string operator+(L left, R right) {
std::ostringstream os;
os << left << right;
return os.str();
}



Then you can write your concatenations in a straightforward way:


std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);
std::cout << bar << std::endl;



Output:


the answer is 42



This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.





If I try to add to integers or an integer and a double, will this function be called ? I am wondering if this solution will override the usual additions...
– Hilder Vitor Lima Pereira
Jan 14 '16 at 15:30





The operator returns a std::string, so wouldn't be a candidate in expressions where a string isn't convertible into the needed type. E.g., this operator+ isn't eligible to be used for + in int x = 5 + 7;. All things considered, I wouldn't define an operator like this without a very compelling reason, but my aim was to offer an answer different from the others.
– uckelman
Jan 15 '16 at 15:14


std::string


operator+


+


int x = 5 + 7;





You are right (I just tested it...). And when I tried to do something like string s = 5 + 7, I got the error invalid conversion from ‘int’ to ‘const char’*
– Hilder Vitor Lima Pereira
Jan 15 '16 at 17:55



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.



The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:


#include <sstream>
#define MAKE_STRING(tokens) /****************/
static_cast<std::ostringstream&>(
std::ostringstream().flush() << tokens
).str()
/**/



Now you can format strings like this:


int main() {
int i = 123;
std::string message = MAKE_STRING("i = " << i);
std::cout << message << std::endl; // prints: "i = 123"
}





Ick. I think I'd rather use an inline function, thank you.
– T.E.D.
Nov 19 '08 at 14:48



As a Qt-related question was closed in favour of this one, here's how to do it using Qt:


QString string = QString("Some string %1 with an int somewhere").arg(someIntVariable);
string.append(someOtherIntVariable);



The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.





QString("Something ") + QString::number(someIntVariable) also works
– gremwell
Aug 7 '17 at 4:33



You can concatinate int to string by using the given below simple trick, but note that this only works when integer is of single digit otherwise add integer digit by digit to that string.


string name = "John";
int age = 5;
char temp=5+'0';
name=name+temp;
cout<<name<<endl;

Output:- John5



Common Answer: itoa()



This is bad. itoa is non-standard, as pointed out here.


itoa





itoa is non standard: stackoverflow.com/questions/190229/…
– David Dibben
Oct 10 '08 at 15:11





iota is in the numeric header as of C++11.
– uckelman
Jan 12 '12 at 11:42


numeric





@uckelman iota != itoa
– emlai
Oct 20 '15 at 13:41



There are more options possible to use to concatenate integer (or other numerric object) with string. It is Boost.Format


#include <boost/format.hpp>
#include <string>
int main()
{
using boost::format;

int age = 22;
std::string str_age = str(format("age is %1%") % age);
}



and Karma from Boost.Spirit (v2)


#include <boost/spirit/include/karma.hpp>
#include <iterator>
#include <string>
int main()
{
using namespace boost::spirit;

int age = 22;
std::string str_age("age is ");
std::back_insert_iterator<std::string> sink(str_age);
karma::generate(sink, int_, age);

return 0;
}



Boost.Spirit Karma claims to be one of the fastest option for integer to string conversion.



If you want to get a char* out, and have used stringstream as per what the above respondants have outlined, then do e.g.:


myFuncWhichTakesPtrToChar(ss.str().c_str());



Since what the stringstream returns via str() is a standard string, you can then call c_str() on that to get your desired output type.



There is a function I wrote, which takes in parameters the int number, and convert it to a string literal, this function is dependant on another function that converts a single digit to its char equivalent :


char intToChar ( int num)
{
if ( num < 10 && num >= 0)
{
return num + 48;
//48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)
}
else
{
return '*';
}
}

string intToString ( int num)
{
int digits = 0, process, single;
string numString;
process = num;

//The following process the number of digits in num
while ( process != 0)
{
single = process % 10; // single now hold the rightmost portion of the int
process = (process - single)/10;
// take out the rightmost number of the int ( it's a zero in this portion of the int), then divide it by 10
// The above combinasion eliminates the rightmost portion of the int
digits ++;
}

process = num;

//Fill the numString with '*' times digits
for ( int i = 0; i < digits; i++)
{
numString += '*';
}


for ( int i = digits-1; i >= 0; i-- )
{
single = process % 10;
numString[i] = intToChar ( single);
process = ( process - single) / 10;
}

return numString;
}



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
}



Another easy way of doing it is:


name.append(age+"");
cout << name;





I don't get how this got upvoted 5 times...This doesn't even compile!
– 0x499602D2
Dec 31 '13 at 16:01





Actually, it does compile but it invokes undefined behavior
– 0x499602D2
Mar 20 '14 at 20:35





You're decaying the string literal "" to a char* and incrementing that pointer by age. In other words, undefined behavior.
– emlai
Oct 20 '15 at 13:46


""


char*


age





This is very much wrong.
– Baum mit Augen
Dec 15 '16 at 15:48



Without C++11, for a small integer range, I found this is all I needed:



declare/include some variant of the following somewhere:


const string intToString[10] = {"0","1","2","3","4","5","6","7","8","9"};



then:


string str = intToString[3]+" + "+intToString[4]+" = "+intToString[7]; //str equals "3 + 4 = 7"



Works with enums too.



The detailed answer is buried in below other answers, resurfacing part of it:


#include <iostream> // cout
#include <string> // string, to_string(some_number_here)

using namespace std;

int main() {
// using constants
cout << "John" + std::to_string(21) << endl;
// output is:
// John21

// using variables
string name = "John";
int age = 21;
cout << name + to_string(age) << endl;
// output is:
// John21
}



With the {fmt} library:


auto result = fmt::format("{}{}", name, age);



A subset of the library is proposed for standardization as P0645 Text Formatting and, if accepted, the above will become:


auto result = std::format("{}{}", name, age);



Disclaimer: I'm the author of the {fmt} library.



This problem can be done in manys ways,i will show in two ways :-



1).Convert the number to string using to_string(i).



2). Using string streams .



Code :-


#include <string>
#include <sstream>
#include<bits/stdc++.h>
#include<iostream>
using namespace std;

int main(){
string name = "John";
int age=21;

string answer1="";
// Method 1). string s1=to_string(age).

string s1=to_string(age); // know the integer get converted into string
// where as we know that concatenation can easily be done using '+' in c++

answer1=name+s1;

cout<<answer1<<endl;

// Method 2).Using string streams

ostringstream s2;

s2 << age;

string s3 = s2.str(); // the str() function will coverts number into string

string answer2=""; // for concatenation of strings.

answer2=name+s3;

cout<<answer2<<endl;

return 0;
}



// Hope it helps



Suggesting an alternate solution for people like me who may not have access to C++ 11 and additional libraries/headers like boost. A simple conversion works like this:

Example the number is 4, to convert 3 into ascii we can simply use the code:
char a='0'+4


This will immediately store 4 as a character in a.

From here, we can simply concatenate a with the rest of the string.



I am a beginner C++ user and found this the easiest way:


cout << name << age;



This will successfully concatenate name and age, the the output will be "John21."



However there has to be a reason nobody said this; I think there may be a flaw in it although I haven't experienced any so far.



EDIT: I have realized that this is not necessarily the right answer, however I will keep it here in case any C++ beginners would like to know how to output concatenated strings.





This is just output two strings together, not building up a new string. So for example you cannot pass the result to another functions. This is not an answer.
– Earth Engine
Oct 2 '14 at 2:12





Ah, I didn't interpret OP's question correctly, in that case. But IOStream would work, correct?
– Admin Voter
Oct 2 '14 at 13:50






This could be easily converted to a good answer to the OP's question if you invoked stringstreams....
– Hurkyl
Sep 27 '15 at 22:47


stringstream





@Hurkyl However, we already have that in the other answers.
– Baum mit Augen
Dec 15 '16 at 15:47






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

how to run turtle graphics in Colaboratory

Export result set on Dbeaver to CSV