The error with your original code has to do with how you call
itoa(). You pass the same buffer parameter to both calls.
The sequence of statements you wrote...
Code: Select all
std::string u = itoa(numUnits, num, 10) + std::string(" | ") + itoa(unitLimit, num, 10);
I can't remember the rules of sequence points off of the top of my head, but what is happening is that both
itoa() calls are completed before the
operator+() calls are started. The following is roughly equivalent and should illustrate the problem...
Code: Select all
// stores the string representation of numUnits in the buffer `num'
const char* strNumUnits = itoa(numUnits, num, 10);
printf ("numUnits = %s\n", strNumUnits);
// stores the string representation of unitLimit in the buffer `num'
// overwriting what was previously stored in `num'
const char* strUnitLimit = itoa(unitLimit, num, 10);
printf ("numUnits = %s\n", strNumUnits);
printf ("unitLimit = %s\n", strUnitLimit);
std::string u = strNumUnits + std::string(" | ") + strUnitLimit;
The easy way to handle this is to either use a different buffer for each
itoa() call, or to break up the expression so that the buffer is read before it is overwritten.
Code: Select all
std::string u
u += itoa(numUnits, num, 10);
u += " | "
u += itoa(unitLimit, num, 10);
Another simple option is to use one of the
sprintf family of functions...
Code: Select all
#include <stdio.h>
#include <string>
int main ()
{
int numUnits = 1;
int unitLimit = 12;
char buf [64];
sprintf (buf, "%d | %d", numUnits, unitLimit);
std::string u (buf);
std::cout << u << std::endl;
return 0;
}
You could also use this...
Code: Select all
#include <sstream>
#include <string>
int main ()
{
int numUnits = 1;
int unitLimit = 12;
std::ostringstream os;
os << numUnits << " | " << unitLimit;
std::string u (os.str());
std::cout << u << std::endl;
return 0;
}
Or you could even use Irrlicht's string class...
Code: Select all
#include <irrlicht.h>
using namespace irr;
int main ()
{
int numUnits = 1;
int unitLimit = 12;
core::string u;
u += numUnits;
u += " | ";
u += unitLimit;
std::string u (u.c_str());
std::cout << u << std::endl;
return 0;
}
Travis