Thursday, July 30, 2009

C++: Cocatenating an int to the end of a string?

I need to know how to concatenate an int to a string, the simplist way possible.





Here is a snippet of my code (only elementCoefficients[index] is an int) :





string buildChemicalFormula(int elementCoefficients[])


{


string formula = "";


int index;


for(index = 0; index %26lt; numberOfElements; index++)


formula = formula + elements[index].chemicalSymbol + elementCoefficients[index];





size_t location;


size_t index1;


for(index1 = 0; index1 %26lt; formula.length(); index1++)


{


location = formula.find("0", 0);


if(location !=string::npos)


{


formula.erase(location-1, 2);


index1 = index1 - 2;


}


}





return formula;


}





When I try to create the new formula, the compiler outputs, " error C2676: binary '+' : 'std::basic_string%26lt;_Elem,_Traits,_Ax%26gt;' does not define this operator or a conversion to a type acceptable to the predefined operator".





I tried casting the ints to chars but didn't work.

C++: Cocatenating an int to the end of a string?
You should be able to use the itoa() function (integer to alpha). Here's more information. http://www.cplusplus.com/reference/clibr...
Reply:Do all your additions as int. When you are ready to print the string, use string + int and it will do automatic string conversion.


No comments:

Post a Comment