Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error -- expression must have integral or enum type -- getting this from a string with concatenation?

Tags:

c++

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?

like image 361
SuperCow Avatar asked Mar 31 '14 03:03

SuperCow


2 Answers

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

like image 100
Ferruccio Avatar answered Oct 19 '22 20:10

Ferruccio


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();
like image 32
SHR Avatar answered Oct 19 '22 22:10

SHR