user37875
user37875

Reputation: 14194

Append an int to char*

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

Upvotes: 26

Views: 80489

Answers (3)

Paige Ruten
Paige Ruten

Reputation: 176645

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"

Upvotes: 29

Sydius
Sydius

Reputation: 14257

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

Upvotes: 10

Draemon
Draemon

Reputation: 34711

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.

Upvotes: 4

Related Questions