Question

[Solved] C++ error — expression must have integral or enum type — getting this from a string with concatenation?

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?

Enquirer: SuperCow

||

Solution #1:

"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.

Respondent: Ferruccio

Solution #2:

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();
Respondent: SHR

Solution #3:

Try std::to_string(getBags()). You can only concatenate strings with strings.

Respondent: Lee Thomas

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy