Skip to content

adding a string and int to a string

An answer to this question on Stack Overflow.

Question

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

Answer

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.