integer to std::string

Hi guys,

I am working on a project and I am having difficulty getting the following to work..

Logger::log("Player created, level " + player->getLevel());

getLevel() returns a short integer. However, I don't get the players level and the first character in the string is removed.. How can I convert an integer into an std::string? Or is there a better way to go about doing this?
1
2
3
4
5
6
7
#include <sstream>

int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();


I don't get why the first character is removed though.


The first character isn't so much removed as skipped.

You've got "this is a string const" + this_is_an_int
which translates to addr_of_string_const + value_of_an_int

If getLevel() returns 1, then you have addr_of_string_const + 1
which is the same as addr_of_second_char_in_string_const
:-)

BTW. I don't know how you got that to compile without seeing some pretty dire warnings. Make sure you turn all warnings on when you compile so that things like this are found.

Hope this helps.
Thanks for the help, it makes a lot more sense now.
If it helps, there is a function itoa:

char * itoa ( int value, char * str, int base );

Parameters

value
Value to be converted to a string.
str
Array in memory where to store the resulting null-terminated string.
base
Numerical base used to represent the value as a string, between 2 and 36, where 10 means decimal base, 16 hexadecimal, 8 octal, and 2 binary.

more details can be found here:

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html

it will convert the integer to a char pointer.
Topic archived. No new replies allowed.