0

Possible Duplicate:
Append an int to a std::string

I want to add string and int into my string.

In my LocationData::toString() method , i am trying to add a bunch of things together into my string str.

It adds the first input which is a string sunType, and it adds a second input, a integer. There is no problem in compiling, but when i run my code, the output is

Sun Type: sunNo Of Earth Like Planets:

which it should be

Sun Type:

No Of Earth Like Planets:

so is there something wrong with my code? I didnt show my whole code as it is some how lengthy. Hope someone can answer me thanks !

#include <iostream>
#include <string>

using namespace std;

class LocationData
{   
    private:
    string sunType;
    int noOfEarthLikePlanets;
    int noOfEarthLikeMoons;
    float aveParticulateDensity;
    float avePlasmaDensity;
    public:
    string toString();

};

string LocationData::toString()
{
    string str = "Sun Type: " + getSunType();
    str += "\nNo Of Earth Like Planets: " + getNoOfEarthLikePlanets();
    //str += "\nNo Of Earth Like Moons: " + getNoOfEarthLikeMoons();
    //str += "\nAve Particulate Density: " + getAveParticulateDensity();
    //str += "\nAve Plasma Density: " + getAvePlasmaDensity();
    return str;
}

int main()
{

    cout<<test.toString()<<endl;
}
Community
  • 1
  • 1
Heng Aik Hwee
  • 159
  • 1
  • 4
  • 13
  • 3
    For possibilities on adding an `int` to a `std::string` see http://stackoverflow.com/questions/10516196/append-an-int-to-a-stdstring/10516313#10516313 – hmjd Oct 16 '12 at 11:24

2 Answers2

3

You are adding an integer to character pointer which advances a pointer by the said number. Use std::stringstream to do this instead of doing all kinds of conversions. Something like this:

std::stringstream ss;
ss << "Sun Type: " << getSunType() << "\nNo Of Earth Like Planets: "<<getNoOfEarthLikePlanets();
std::string s = ss.str();
Asha
  • 11,002
  • 6
  • 44
  • 66
  • er this was suppose to be written in my main right? This is a homework in school which i am suppose to do all those in my toString method , and in my main method than i will call it and display according – Heng Aik Hwee Oct 16 '12 at 11:33
1

An MWE using stringstream:

#include <sstream>
#include <iostream>
using namespace std;

int main(){
    stringstream ss;
    int i=40;
    ss<<"Hi ";
    ss<<i;
    ss<<"bye";
    cout<<ss.str()<<endl;
}

outputs "Hi 40bye", as expected.

See also this question.

Community
  • 1
  • 1
Richard
  • 56,349
  • 34
  • 180
  • 251