-2

I am trying to create a string that calls functions and concatenates the return string values. If one of the functions returns an int I get an error. I don't have much experience with overloading operators, but I'm thinking I need to overload the + operator to make this work. Is this correct? Or is there a better way to do this?

string str=getString1()+getString2()+getInt();
Jordan
  • 3
  • 1

2 Answers2

4

You can use std::to_string.

string str = getString1() + getString2() + std::to_string(getInt());
jrok
  • 54,456
  • 9
  • 109
  • 141
vincentp
  • 1,433
  • 9
  • 12
0

Using std::to_string as suggested by vincent you could also overload the + operator in an easy way:

// string + int
std::string operator+(const std::string &str, const int &i){
    std::string result = str + std::to_string(i);
    return result;
}
// int + string
std::string operator+(const int &i, const std::string &str){
    std::string result = std::to_string(i) + str;
    return result;
}

Then your original code should work as espected.

string str = getString1() + getString2() + getInt();

Example:

td::cout << string("This is a number: ") + 5 << endl;
std::cout << 5 + string(" is a number.") << endl;

Output:

This is a number: 5
5 is a number.
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60