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
2008-12-07 02:40:46
This will also work in C.
Sydius
2008-12-07 02:46:24
You have a buffer overflow vulnerability on your hands if sizeof(int) > 4.
Tom
2008-12-07 02:47:29
Yeah, this is really insecure. At least use strncat...
Jason Coco
2008-12-07 02:56:30
@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
2008-12-07 03:28:44
Should use snprintf and strncat, just to be safe.
Brian C. Lane
2008-12-07 03:55:53
why not do it all via the sprintf?? snprintf(other_string, 64, "Interger: %d", integer);
Lodle
2008-12-07 03:58:06
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
2008-12-07 05:30:59
For added portability, multiply that factor 3 by CHAR_BITS/8.
MSalters
2008-12-08 10:08:00
+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
2008-12-07 02:45:29
+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
2008-12-07 02:50:26