1

I'm trying to add int to string in a return statement like so:

string Birthday::asString() {
    return this -> day + "/" + this -> month + "/" + this -> year;
}

and getting the following error:

Error: expression must have integral or unscoped enum type

I'm kind of new to C++.

3
  • 2
    sscce.org. Or, in other words: Neither "string" nor "Birthday" nor "this" nor "day" nor "month" nor "year" are actually defined in the code snippet you have posted. Commented Apr 25, 2013 at 12:28
  • 3
    What are the types of day, month and year? Commented Apr 25, 2013 at 12:29
  • Also, this is the first time I saw anyone putting spaces between operands of ->. Commented Apr 25, 2013 at 13:55

2 Answers 2

11

Easiest way to do what you are trying to do is to use ostringstream(found in header <sstream>):

string Birthday::asString() {
    std::ostringstream out;
    out << this -> day << "/" << this -> month << "/" << this -> year;
    return out.str();
}

You are getting the error you show because C++ does not know how to add an integer to a string.

EDIT: as suggest in M M.'s answer since C++11 there is another option, namely to use the function std::to_string.

Sign up to request clarification or add additional context in comments.

7 Comments

Is there a way for doing this without creating an object ? I think that is a better practice
@user1970719 you need to convert the integers to strings so you will need to create a new object.
@user1970719: The object being the ostringstream instance? Actually the ostringstream solution is superior in terms of performance than the std::to_string solution.
No, the easiest way is to use std::to_string. Yes it is C++11, but this is the current standard (and thus the default) so you should probably mention that your solution is for the older C++03.
@syam though I agree I must mention this alternative(and I already did in an edit) I still think what I suggest is a bit easier to both read and write in this case.
|
7

You can use std::to_string:

string Birthday::asString() {
     return std::to_string(this->day) + "/" +
            std::to_string(this->month) + "/" +
            std::to_string(this->year);
}

Available since C++11

1 Comment

It is also available in not yet c++11 MSVC10 It lacks some C++11 overloads thru and may require some casts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.