Append an int to char*


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

8/18/2017 3:52:59 PM

Accepted Answer

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"
8/18/2017 3:52:50 PM

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();

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow