How would you append an integer to a char*
in c++?
Asked
Active
Viewed 7.8k times
3 Answers
29
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"

Vadim Kotov
- 8,084
- 8
- 48
- 62

Paige Ruten
- 172,675
- 36
- 177
- 197
-
You have a buffer overflow vulnerability on your hands if sizeof(int) > 4. – Tom Dec 07 '08 at 02:47
-
@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. – Paige Ruten Dec 07 '08 at 03:28
-
Should use snprintf and strncat, just to be safe. – Brian C. Lane Dec 07 '08 at 03:55
-
why not do it all via the sprintf?? snprintf(other_string, 64, "Interger: %d", integer); – Lodle Dec 07 '08 at 03:58
-
Instead of using a fixed constant size for the string, you might want to use something like
+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 Dec 07 '08 at 05:30 -
For added portability, multiply that factor 3 by CHAR_BITS/8. – MSalters Dec 08 '08 at 10:08
-
This is quite old. I tried and it show 'unsafe to use' on strcat and sprintf. Any latest answer would be good. – Leo May 04 '22 at 01:24
10
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();

Vadim Kotov
- 8,084
- 8
- 48
- 62

Sydius
- 13,567
- 17
- 59
- 76
4
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
- 33,955
- 16
- 77
- 104