C++ error expression must have integral or enum type getting this from a string with concatenation?
So in the toString()
of a class in C++ I have the code:
string bags = "Check in " + getBags() + " bags";
I thought I could declare a string like this? (I'm coming from a Java background and trying to learn C++). The bags
is underlined in Visual Studio though and the problem is:
expression must have integral or enum type.
getBags()
just returns an int
.
Another example where this happens is with:
string totalPrice = "Grand Total: " + getTotalPrice();
getTotalPrice()
returns a float
and is what is underlined with the error.
But then if I put in a line like:
string blah = getBags() + "blah";
No errors.
What am I not understanding here?
"Check in "
is actually a const char *
.
Adding getBags()
(an int
) to it yields another const char*
. The compiler error is generated because you cannot add two pointers.
You need to convert both "Check in "
and getBags()
to strings before concatenating them:
string bags = std::string("Check in ") + std::to_string(getBags()) + " bags";
" bags"
will be implicitly converted to a string
.
when using + to append strings the first element must have operator+, const char* doesn't have it.
therefore you should to make a string from it:
string bags = string("Check in ") + getBags() + " bags";
or to do it in to steps:
string bags = string("Check in ") + getBags() + " bags";
EDIT: More problem is the int returned from the method, for some reason, string doesn't have operator+ for int.
So you better use stringstream like this:
#include <sstream>
....
ostringstream s;
s<<"Check in " << getBags() << " bags";
string bags = s.str();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With