0

I need to write a function concat like:

std::string concat(...);

that accepts any number of arguments of varying types(char, char*, int, std::string, ...) and returns their concatenation. for example:

concat(88,'a',"home",9) == std::string("88ahome9")
simon-f
  • 95
  • 6
  • 2
    This is a combination of two questions. 1) How to allow a varying number of arguments in a function call. [See here](http://stackoverflow.com/questions/1657883/variable-number-of-arguments-in-c). 2) How to concatenate various string types. That question is very basic, there are dozens of examples online if you search. – Cory Kramer Jul 22 '14 at 11:40
  • 1
    You might want to read about [template prameter packs](http://en.cppreference.com/w/cpp/language/parameter_pack) and [`std::ostringstream`](http://en.cppreference.com/w/cpp/io/basic_ostringstream). – Some programmer dude Jul 22 '14 at 11:42
  • See http://stackoverflow.com/questions/662918/how-do-i-concatenate-multiple-c-strings-on-one-line/23910249#23910249, my answer there provides what you ask for. – SebastianK Jul 22 '14 at 11:54

2 Answers2

6

You may use the following:

template<typename ... Ts>
std::string concat(Ts&&...args)
{
    std::stringstream ss;
    const int dummy[] = {0, (ss << std::forward<Ts>(args), 0)...};
    static_cast<void>(dummy);  // avoid warning for unused variable
    return ss.str();
}

Live example

or in C++17, with Folding expression

template<typename ... Ts>
std::string concat(Ts&&...args)
{
    std::stringstream ss;
    (ss << ... << std::forward<Ts>(args));
    return ss.str();
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

You could use the ostringstream convert function in the sstream library.

You would start with a line such as

ostringstream convert;

Then with the << operator convert the variable you wish(or >> to convert from string), like:

int var = 98;

convert << var;

Then store this in a string:

string result;

result = convert.str();

That string will now contain the contents of your int!

Ofc you can use if statements to differentiate between input as chars, ints, etc. And combine all the strings at the end to concate them.

Btw sorry for spelling and format, on phone xD

23scurtu
  • 138
  • 10