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;
}
1

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.