-1

This may seem trivial to normal C++ users, but I'm currently relearning C++ all over again. I have a function that takes in an int& and I would like to add that value to a string for a print statement. So, I have something like this:

std::string getTest(void* dataGroup, int& xWidth, int& yHeight)
{
     std::string results = "";

     results += "\nxWidth is: " + xWidth;

     return results;
}

which fails to run when I call it. What is the proper way to convert the pass-by-reference int& value into a form that can be added to a string?

Roka545
  • 3,404
  • 20
  • 62
  • 106
  • You cannot do this. Use e.g.: `results += "\nxWidth is: " + std::to_string(xWidth);`. Please consider to do a bit more research before posting here. ` – πάντα ῥεῖ Dec 21 '16 at 17:15
  • 1
    http://en.cppreference.com/w/cpp/string/basic_string/to_string, http://stackoverflow.com/questions/5590381/easiest-way-to-convert-int-to-string-in-c, http://stackoverflow.com/questions/29333397/how-to-convert-int-to-string, – chris Dec 21 '16 at 17:16
  • One of the sides of the `+` operator must be of type `std::string` for that to work. You have `const char const *` and `int&`. They are incompatible types. Did you take a look at the error message your compiler should be throwing? – Qix - MONICA WAS MISTREATED Dec 21 '16 at 17:23

1 Answers1

3

std::to_string(xWidth).

The & is pretty much irrelevant. to_string takes the int by value, so how your function takes it doesn't matter: by value, lvalue ref, rvalue ref, const or non-const... all will work.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • Should also be noted that taking an `int&` in this case is pointless since you're not changing it and it'll ultimately be the same size (maybe even smaller in certain cases) to pass it as value. – Qix - MONICA WAS MISTREATED Dec 21 '16 at 17:24