views:

1778

answers:

4

How would you append an integer to a char* in c++?

+2  A: 

First convert the int to a char* using sprintf():

char integer_string[32];
int integer = 1234;

sprintf(integer_string, "%d", integer);

Then to append it to your other char*, use strcat():

char other_string[64] = "Integer: "; // make sure you allocate enough space to append the other string

strcat(other_string, integer_string); // other_string now contains "Integer: 1234"
yjerem
This will also work in C.
Sydius
You have a buffer overflow vulnerability on your hands if sizeof(int) > 4.
Tom
Yeah, this is really insecure. At least use strncat...
Jason Coco
@Tom: I'm not used to using the int type (I always use types like u8, u16, u32, etc.) so I didn't think of that... I will change the size of the string then.
yjerem
Should use snprintf and strncat, just to be safe.
Brian C. Lane
why not do it all via the sprintf?? snprintf(other_string, 64, "Interger: %d", integer);
Lodle
Instead of using a fixed constant size for the string, you might want to use something like <base size>+sizeof(int)*3+1 (3 = ceil(8*log10(2)), 1 for '-'). This should always work (also in case of 128-bit ints etc.) and also avoids unnecessarily large allocations (probably not an issue).
mweerden
For added portability, multiply that factor 3 by CHAR_BITS/8.
MSalters
A: 

Thank you very much!

This should be an edit to your original post rather than an answer
Draemon
+6  A: 

You could also use stringstreams.

char *theString = "Some string";
int theInt = 5;
stringstream ss;
ss << theString << theInt;

The string can then be accessed using ss.str();

Sydius
+1  A: 

Something like:

width = floor(log10(num))+1;
result = malloc(strlen(str)+len));
sprintf(result, "%s%*d", str, width, num);

You could simplify len by using the maximum length for an integer on your system.

edit oops - didn't see the "++". Still, it's an alternative.

Draemon