Apr 19, 2018 at 9:21pm UTC
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 Apr 19, 2018 at 9:21pm UTC
Apr 19, 2018 at 9:31pm UTC
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 Apr 19, 2018 at 9:32pm UTC
Apr 20, 2018 at 3:16pm UTC
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.
Apr 25, 2018 at 1:37pm UTC
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 Apr 25, 2018 at 4:37pm UTC