Simplest way to concatenate String + Int?

I have a String and Int that I want to concatenate together. An example:

1
2
  String a = XY4THFUD39TH
  int b = 7644500


where the outcome should become XY4THFUD39TH7644500. It can be stored as any data type.

What is the most efficient of doing this?
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main(){
    std::string a = "XY4THFUD39TH";
    int b = 7644500;
    
    a = a+std::to_string(b);
    std::cout << a;

    return 0;
}
Last edited on
closed account (E0p9LyTq)
Simplest way to concatenate String + Int?
1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
#include <string>

int main()
{ 
   std::string aString = "XY4THFUD39TH";
   int aNumber = 7644500;

   std::string aConcat = aString + std::to_string(aNumber);

   std::cout << aConcat << '\n';
}

It can be stored as any data type.

The concatenation can only be stored as a C++ std::string or a C-style char array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
using namespace std;

string operator+( string s, int i ){ return s + to_string( i ); }

int main()
{
   string a = "XY4THFUD39TH";
   int b = 7644500;

   string result = a + b;
   cout << result;
}

the most efficient way to do it is to not do it.

if, as in your example, you know at the code writing time what the values are:

String a = XY4THFUD39TH
int b = 7644500

then just do this

String a = XY4THFUD39TH7644500

because the conversion from a number to text is a fair bit of work behind the scenes.

If you do NOT know the values at compile time, you do need to convert them as shown, eg
cin >> b; //unknown value, must be converted.

you can also do it with stringstreams. Depending on what you need done, those may or may not be a better approach.


Doing this with std::ostringstream:

1
2
3
4
5
string concatenate(const string& str, int num) {
  ostringstream oss;
  oss << str << num;
  return oss.str();
}
Variadic style

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
#include <sstream>

template <typename T>
std::string Cat(T arg)
{
	std::stringstream ss;
	ss << arg;
	return ss.str();
}

template <typename T, typename... Args>
std::string Cat(T current, Args... args)
{
	std::string result;
	result += Cat(current);
	result += Cat((args)...);
	return result;
}

int main()
{
	std::cout << Cat("hello ",1.0," world!\n");
    return 0;
}
Last edited on
Topic archived. No new replies allowed.